]> git.lizzy.rs Git - minetest.git/blob - src/gui/guiFormSpecMenu.cpp
Remove dead code (#10845)
[minetest.git] / src / gui / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <limits>
25 #include <sstream>
26 #include "guiFormSpecMenu.h"
27 #include "constants.h"
28 #include "gamedef.h"
29 #include "client/keycode.h"
30 #include "util/strfnd.h"
31 #include <IGUIButton.h>
32 #include <IGUICheckBox.h>
33 #include <IGUIComboBox.h>
34 #include <IGUIEditBox.h>
35 #include <IGUIStaticText.h>
36 #include <IGUIFont.h>
37 #include <IGUITabControl.h>
38 #include "client/renderingengine.h"
39 #include "log.h"
40 #include "client/tile.h" // ITextureSource
41 #include "client/hud.h" // drawItemStack
42 #include "filesys.h"
43 #include "gettime.h"
44 #include "gettext.h"
45 #include "scripting_server.h"
46 #include "mainmenumanager.h"
47 #include "porting.h"
48 #include "settings.h"
49 #include "client/client.h"
50 #include "client/fontengine.h"
51 #include "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() > 9 &&
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() < 9)
2737                 parts.resize(9);
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         std::vector<std::string> frame_loop = split(parts[8], ',');
2748
2749         MY_CHECKPOS("model", 0);
2750         MY_CHECKGEOM("model", 1);
2751
2752         v2s32 pos;
2753         v2s32 geom;
2754
2755         if (data->real_coordinates) {
2756                 pos = getRealCoordinateBasePos(v_pos);
2757                 geom = getRealCoordinateGeometry(v_geom);
2758         } else {
2759                 pos = getElementBasePos(&v_pos);
2760                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
2761                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
2762         }
2763
2764         if (!data->explicit_size)
2765                 warningstream << "invalid use of model without a size[] element" << std::endl;
2766
2767         scene::IAnimatedMesh *mesh = m_client->getMesh(meshstr);
2768
2769         if (!mesh) {
2770                 errorstream << "Invalid model element: Unable to load mesh:"
2771                                 << std::endl << "\t" << meshstr << std::endl;
2772                 return;
2773         }
2774
2775         FieldSpec spec(
2776                 name,
2777                 L"",
2778                 L"",
2779                 258 + m_fields.size()
2780         );
2781
2782         core::rect<s32> rect(pos, pos + geom);
2783
2784         GUIScene *e = new GUIScene(Environment, RenderingEngine::get_scene_manager(),
2785                         data->current_parent, rect, spec.fid);
2786
2787         auto meshnode = e->setMesh(mesh);
2788
2789         for (u32 i = 0; i < textures.size() && i < meshnode->getMaterialCount(); ++i)
2790                 e->setTexture(i, m_tsrc->getTexture(unescape_string(textures[i])));
2791
2792         if (vec_rot.size() >= 2)
2793                 e->setRotation(v2f(stof(vec_rot[0]), stof(vec_rot[1])));
2794
2795         e->enableContinuousRotation(inf_rotation);
2796         e->enableMouseControl(mousectrl);
2797
2798         s32 frame_loop_begin = 0;
2799         s32 frame_loop_end = 0x7FFFFFFF;
2800
2801         if (frame_loop.size() == 2) {
2802             frame_loop_begin = stoi(frame_loop[0]);
2803             frame_loop_end = stoi(frame_loop[1]);
2804         }
2805
2806         e->setFrameLoop(frame_loop_begin, frame_loop_end);
2807
2808         auto style = getStyleForElement("model", spec.fname);
2809         e->setStyles(style);
2810         e->drop();
2811
2812         m_fields.push_back(spec);
2813 }
2814
2815 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2816 {
2817         //some prechecks
2818         if (element.empty())
2819                 return;
2820
2821         if (parseVersionDirect(element))
2822                 return;
2823
2824         size_t pos = element.find('[');
2825         if (pos == std::string::npos)
2826                 return;
2827
2828         std::string type = trim(element.substr(0, pos));
2829         std::string description = element.substr(pos+1);
2830
2831         if (type == "container") {
2832                 parseContainer(data, description);
2833                 return;
2834         }
2835
2836         if (type == "container_end") {
2837                 parseContainerEnd(data);
2838                 return;
2839         }
2840
2841         if (type == "list") {
2842                 parseList(data, description);
2843                 return;
2844         }
2845
2846         if (type == "listring") {
2847                 parseListRing(data, description);
2848                 return;
2849         }
2850
2851         if (type == "checkbox") {
2852                 parseCheckbox(data, description);
2853                 return;
2854         }
2855
2856         if (type == "image") {
2857                 parseImage(data, description);
2858                 return;
2859         }
2860
2861         if (type == "animated_image") {
2862                 parseAnimatedImage(data, description);
2863                 return;
2864         }
2865
2866         if (type == "item_image") {
2867                 parseItemImage(data, description);
2868                 return;
2869         }
2870
2871         if (type == "button" || type == "button_exit") {
2872                 parseButton(data, description, type);
2873                 return;
2874         }
2875
2876         if (type == "background" || type == "background9") {
2877                 parseBackground(data, description);
2878                 return;
2879         }
2880
2881         if (type == "tableoptions"){
2882                 parseTableOptions(data,description);
2883                 return;
2884         }
2885
2886         if (type == "tablecolumns"){
2887                 parseTableColumns(data,description);
2888                 return;
2889         }
2890
2891         if (type == "table"){
2892                 parseTable(data,description);
2893                 return;
2894         }
2895
2896         if (type == "textlist"){
2897                 parseTextList(data,description);
2898                 return;
2899         }
2900
2901         if (type == "dropdown"){
2902                 parseDropDown(data,description);
2903                 return;
2904         }
2905
2906         if (type == "field_close_on_enter") {
2907                 parseFieldCloseOnEnter(data, description);
2908                 return;
2909         }
2910
2911         if (type == "pwdfield") {
2912                 parsePwdField(data,description);
2913                 return;
2914         }
2915
2916         if ((type == "field") || (type == "textarea")){
2917                 parseField(data,description,type);
2918                 return;
2919         }
2920
2921         if (type == "hypertext") {
2922                 parseHyperText(data,description);
2923                 return;
2924         }
2925
2926         if (type == "label") {
2927                 parseLabel(data,description);
2928                 return;
2929         }
2930
2931         if (type == "vertlabel") {
2932                 parseVertLabel(data,description);
2933                 return;
2934         }
2935
2936         if (type == "item_image_button") {
2937                 parseItemImageButton(data,description);
2938                 return;
2939         }
2940
2941         if ((type == "image_button") || (type == "image_button_exit")) {
2942                 parseImageButton(data,description,type);
2943                 return;
2944         }
2945
2946         if (type == "tabheader") {
2947                 parseTabHeader(data,description);
2948                 return;
2949         }
2950
2951         if (type == "box") {
2952                 parseBox(data,description);
2953                 return;
2954         }
2955
2956         if (type == "bgcolor") {
2957                 parseBackgroundColor(data,description);
2958                 return;
2959         }
2960
2961         if (type == "listcolors") {
2962                 parseListColors(data,description);
2963                 return;
2964         }
2965
2966         if (type == "tooltip") {
2967                 parseTooltip(data,description);
2968                 return;
2969         }
2970
2971         if (type == "scrollbar") {
2972                 parseScrollBar(data, description);
2973                 return;
2974         }
2975
2976         if (type == "real_coordinates") {
2977                 data->real_coordinates = is_yes(description);
2978                 return;
2979         }
2980
2981         if (type == "style") {
2982                 parseStyle(data, description, false);
2983                 return;
2984         }
2985
2986         if (type == "style_type") {
2987                 parseStyle(data, description, true);
2988                 return;
2989         }
2990
2991         if (type == "scrollbaroptions") {
2992                 parseScrollBarOptions(data, description);
2993                 return;
2994         }
2995
2996         if (type == "scroll_container") {
2997                 parseScrollContainer(data, description);
2998                 return;
2999         }
3000
3001         if (type == "scroll_container_end") {
3002                 parseScrollContainerEnd(data);
3003                 return;
3004         }
3005
3006         if (type == "set_focus") {
3007                 parseSetFocus(description);
3008                 return;
3009         }
3010
3011         if (type == "model") {
3012                 parseModel(data, description);
3013                 return;
3014         }
3015
3016         // Ignore others
3017         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
3018                         << std::endl;
3019 }
3020
3021 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
3022 {
3023         // Useless to regenerate without a screensize
3024         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
3025                 return;
3026         }
3027
3028         parserData mydata;
3029
3030         // Preserve stuff only on same form, not on a new form.
3031         if (m_text_dst->m_formname == m_last_formname) {
3032                 // Preserve tables/textlists
3033                 for (auto &m_table : m_tables) {
3034                         std::string tablename = m_table.first.fname;
3035                         GUITable *table = m_table.second;
3036                         mydata.table_dyndata[tablename] = table->getDynamicData();
3037                 }
3038
3039                 // Preserve focus
3040                 gui::IGUIElement *focused_element = Environment->getFocus();
3041                 if (focused_element && focused_element->getParent() == this) {
3042                         s32 focused_id = focused_element->getID();
3043                         if (focused_id > 257) {
3044                                 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
3045                                         if (field.fid == focused_id) {
3046                                                 m_focused_element = field.fname;
3047                                                 break;
3048                                         }
3049                                 }
3050                         }
3051                 }
3052         } else {
3053                 // Don't keep old focus value
3054                 m_focused_element = "";
3055         }
3056
3057         // Remove children
3058         removeChildren();
3059
3060         for (auto &table_it : m_tables)
3061                 table_it.second->drop();
3062         for (auto &inventorylist_it : m_inventorylists)
3063                 inventorylist_it->drop();
3064         for (auto &checkbox_it : m_checkboxes)
3065                 checkbox_it.second->drop();
3066         for (auto &scrollbar_it : m_scrollbars)
3067                 scrollbar_it.second->drop();
3068         for (auto &background_it : m_backgrounds)
3069                 background_it->drop();
3070         for (auto &tooltip_rect_it : m_tooltip_rects)
3071                 tooltip_rect_it.first->drop();
3072         for (auto &clickthrough_it : m_clickthrough_elements)
3073                 clickthrough_it->drop();
3074         for (auto &scroll_container_it : m_scroll_containers)
3075                 scroll_container_it.second->drop();
3076
3077         mydata.size = v2s32(100, 100);
3078         mydata.screensize = screensize;
3079         mydata.offset = v2f32(0.5f, 0.5f);
3080         mydata.anchor = v2f32(0.5f, 0.5f);
3081         mydata.simple_field_count = 0;
3082
3083         // Base position of contents of form
3084         mydata.basepos = getBasePos();
3085
3086         // the parent for the parsed elements
3087         mydata.current_parent = this;
3088
3089         m_inventorylists.clear();
3090         m_backgrounds.clear();
3091         m_tables.clear();
3092         m_checkboxes.clear();
3093         m_scrollbars.clear();
3094         m_fields.clear();
3095         m_tooltips.clear();
3096         m_tooltip_rects.clear();
3097         m_inventory_rings.clear();
3098         m_dropdowns.clear();
3099         m_scroll_containers.clear();
3100         theme_by_name.clear();
3101         theme_by_type.clear();
3102         m_clickthrough_elements.clear();
3103         field_close_on_enter.clear();
3104         m_dropdown_index_event.clear();
3105
3106         m_bgnonfullscreen = true;
3107         m_bgfullscreen = false;
3108
3109         m_formspec_version = 1;
3110
3111         {
3112                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
3113                 m_bgcolor = video::SColor(
3114                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
3115                         clamp_u8(myround(formspec_bgcolor.X)),
3116                         clamp_u8(myround(formspec_bgcolor.Y)),
3117                         clamp_u8(myround(formspec_bgcolor.Z))
3118                 );
3119         }
3120
3121         {
3122                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
3123                 m_fullscreen_bgcolor = video::SColor(
3124                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
3125                         clamp_u8(myround(formspec_bgcolor.X)),
3126                         clamp_u8(myround(formspec_bgcolor.Y)),
3127                         clamp_u8(myround(formspec_bgcolor.Z))
3128                 );
3129         }
3130
3131         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3132         m_default_tooltip_color = video::SColor(255,255,255,255);
3133
3134         // Add tooltip
3135         {
3136                 assert(!m_tooltip_element);
3137                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3138                 m_tooltip_element = gui::StaticText::add(Environment, L"",
3139                         core::rect<s32>(0, 0, 110, 18));
3140                 m_tooltip_element->enableOverrideColor(true);
3141                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3142                 m_tooltip_element->setDrawBackground(true);
3143                 m_tooltip_element->setDrawBorder(true);
3144                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3145                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3146                 m_tooltip_element->setWordWrap(false);
3147                 //we're not parent so no autograb for this one!
3148                 m_tooltip_element->grab();
3149         }
3150
3151         std::vector<std::string> elements = split(m_formspec_string,']');
3152         unsigned int i = 0;
3153
3154         /* try to read version from first element only */
3155         if (!elements.empty()) {
3156                 if (parseVersionDirect(elements[0])) {
3157                         i++;
3158                 }
3159         }
3160
3161         /* we need size first in order to calculate image scale */
3162         mydata.explicit_size = false;
3163         for (; i< elements.size(); i++) {
3164                 if (!parseSizeDirect(&mydata, elements[i])) {
3165                         break;
3166                 }
3167         }
3168
3169         /* "position" element is always after "size" element if it used */
3170         for (; i< elements.size(); i++) {
3171                 if (!parsePositionDirect(&mydata, elements[i])) {
3172                         break;
3173                 }
3174         }
3175
3176         /* "anchor" element is always after "position" (or  "size" element) if it used */
3177         for (; i< elements.size(); i++) {
3178                 if (!parseAnchorDirect(&mydata, elements[i])) {
3179                         break;
3180                 }
3181         }
3182
3183         /* "no_prepend" element is always after "position" (or  "size" element) if it used */
3184         bool enable_prepends = true;
3185         for (; i < elements.size(); i++) {
3186                 if (elements[i].empty())
3187                         break;
3188
3189                 std::vector<std::string> parts = split(elements[i], '[');
3190                 if (trim(parts[0]) == "no_prepend")
3191                         enable_prepends = false;
3192                 else
3193                         break;
3194         }
3195
3196         /* Copy of the "real_coordinates" element for after the form size. */
3197         mydata.real_coordinates = m_formspec_version >= 2;
3198         for (; i < elements.size(); i++) {
3199                 std::vector<std::string> parts = split(elements[i], '[');
3200                 std::string name = trim(parts[0]);
3201                 if (name != "real_coordinates" || parts.size() != 2)
3202                         break; // Invalid format
3203
3204                 mydata.real_coordinates = is_yes(trim(parts[1]));
3205         }
3206
3207         if (mydata.explicit_size) {
3208                 // compute scaling for specified form size
3209                 if (m_lock) {
3210                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3211                         v2u32 delta = current_screensize - m_lockscreensize;
3212
3213                         if (current_screensize.Y > m_lockscreensize.Y)
3214                                 delta.Y /= 2;
3215                         else
3216                                 delta.Y = 0;
3217
3218                         if (current_screensize.X > m_lockscreensize.X)
3219                                 delta.X /= 2;
3220                         else
3221                                 delta.X = 0;
3222
3223                         offset = v2s32(delta.X,delta.Y);
3224
3225                         mydata.screensize = m_lockscreensize;
3226                 } else {
3227                         offset = v2s32(0,0);
3228                 }
3229
3230                 double gui_scaling = g_settings->getFloat("gui_scaling");
3231                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3232
3233                 double use_imgsize;
3234                 if (m_lock) {
3235                         // In fixed-size mode, inventory image size
3236                         // is 0.53 inch multiplied by the gui_scaling
3237                         // config parameter.  This magic size is chosen
3238                         // to make the main menu (15.5 inventory images
3239                         // wide, including border) just fit into the
3240                         // default window (800 pixels wide) at 96 DPI
3241                         // and default scaling (1.00).
3242                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3243                 } else {
3244                         // Variables for the maximum imgsize that can fit in the screen.
3245                         double fitx_imgsize;
3246                         double fity_imgsize;
3247
3248                         // Pad the screensize with 5% of the screensize on all sides to ensure
3249                         // that even the largest formspecs don't touch the screen borders.
3250                         v2f padded_screensize(
3251                                 mydata.screensize.X * 0.9f,
3252                                 mydata.screensize.Y * 0.9f
3253                         );
3254
3255                         if (mydata.real_coordinates) {
3256                                 fitx_imgsize = padded_screensize.X / mydata.invsize.X;
3257                                 fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
3258                         } else {
3259                                 // The maximum imgsize in the old coordinate system also needs to
3260                                 // factor in padding and spacing along with 0.1 inventory slot spare
3261                                 // and help text space, hence the magic numbers.
3262                                 fitx_imgsize = padded_screensize.X /
3263                                                 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3264                                 fity_imgsize = padded_screensize.Y /
3265                                                 ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
3266                         }
3267
3268 #ifdef __ANDROID__
3269                         // In Android, the preferred imgsize should be larger to accommodate the
3270                         // smaller screensize.
3271                         double prefer_imgsize = padded_screensize.Y / 10 * gui_scaling;
3272 #else
3273                         // Desktop computers have more space, so try to fit 15 coordinates.
3274                         double prefer_imgsize = padded_screensize.Y / 15 * gui_scaling;
3275 #endif
3276                         // Try to use the preferred imgsize, but if that's bigger than the maximum
3277                         // size, use the maximum size.
3278                         use_imgsize = std::min(prefer_imgsize,
3279                                         std::min(fitx_imgsize, fity_imgsize));
3280                 }
3281
3282                 // Everything else is scaled in proportion to the
3283                 // inventory image size.  The inventory slot spacing
3284                 // is 5/4 image size horizontally and 15/13 image size
3285                 // vertically.  The padding around the form (incorporating
3286                 // the border of the outer inventory slots) is 3/8
3287                 // image size.  Font height (baseline to baseline)
3288                 // is 2/5 vertical inventory slot spacing, and button
3289                 // half-height is 7/8 of font height.
3290                 imgsize = v2s32(use_imgsize, use_imgsize);
3291                 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3292                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3293                 m_btn_height = use_imgsize*15.0/13 * 0.35;
3294
3295                 m_font = g_fontengine->getFont();
3296
3297                 if (mydata.real_coordinates) {
3298                         mydata.size = v2s32(
3299                                 mydata.invsize.X*imgsize.X,
3300                                 mydata.invsize.Y*imgsize.Y
3301                         );
3302                 } else {
3303                         mydata.size = v2s32(
3304                                 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3305                                 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3306                         );
3307                 }
3308
3309                 DesiredRect = mydata.rect = core::rect<s32>(
3310                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3311                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3312                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3313                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3314                 );
3315         } else {
3316                 // Non-size[] form must consist only of text fields and
3317                 // implicit "Proceed" button.  Use default font, and
3318                 // temporary form size which will be recalculated below.
3319                 m_font = g_fontengine->getFont();
3320                 m_btn_height = font_line_height(m_font) * 0.875;
3321                 DesiredRect = core::rect<s32>(
3322                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3323                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3324                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3325                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3326                 );
3327         }
3328         recalculateAbsolutePosition(false);
3329         mydata.basepos = getBasePos();
3330         m_tooltip_element->setOverrideFont(m_font);
3331
3332         gui::IGUISkin *skin = Environment->getSkin();
3333         sanity_check(skin);
3334         gui::IGUIFont *old_font = skin->getFont();
3335         skin->setFont(m_font);
3336
3337         pos_offset = v2f32();
3338
3339         // used for formspec versions < 3
3340         core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3341
3342         if (enable_prepends) {
3343                 // Backup the coordinates so that prepends can use the coordinates of choice.
3344                 bool rc_backup = mydata.real_coordinates;
3345                 u16 version_backup = m_formspec_version;
3346                 mydata.real_coordinates = false; // Old coordinates by default.
3347
3348                 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3349                 for (const auto &element : prepend_elements)
3350                         parseElement(&mydata, element);
3351
3352                 // legacy sorting for formspec versions < 3
3353                 if (m_formspec_version >= 3)
3354                         // prepends do not need to be reordered
3355                         legacy_sort_start = Children.getLast();
3356                 else if (version_backup >= 3)
3357                         // only prepends elements have to be reordered
3358                         legacySortElements(legacy_sort_start);
3359
3360                 m_formspec_version = version_backup;
3361                 mydata.real_coordinates = rc_backup; // Restore coordinates
3362         }
3363
3364         for (; i< elements.size(); i++) {
3365                 parseElement(&mydata, elements[i]);
3366         }
3367
3368         if (mydata.current_parent != this) {
3369                 errorstream << "Invalid formspec string: scroll_container was never closed!"
3370                         << std::endl;
3371         } else if (!container_stack.empty()) {
3372                 errorstream << "Invalid formspec string: container was never closed!"
3373                         << std::endl;
3374         }
3375
3376         // get the scrollbar elements for scroll_containers
3377         for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3378                 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3379                         if (c.first == b.first.fname) {
3380                                 c.second->setScrollBar(b.second);
3381                                 break;
3382                         }
3383                 }
3384         }
3385
3386         // If there are fields without explicit size[], add a "Proceed"
3387         // button and adjust size to fit all the fields.
3388         if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3389                 mydata.rect = core::rect<s32>(
3390                                 mydata.screensize.X / 2 - 580 / 2,
3391                                 mydata.screensize.Y / 2 - 300 / 2,
3392                                 mydata.screensize.X / 2 + 580 / 2,
3393                                 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3394                 );
3395
3396                 DesiredRect = mydata.rect;
3397                 recalculateAbsolutePosition(false);
3398                 mydata.basepos = getBasePos();
3399
3400                 {
3401                         v2s32 pos = mydata.basepos;
3402                         pos.Y = (mydata.simple_field_count + 2) * 60;
3403
3404                         v2s32 size = DesiredRect.getSize();
3405                         mydata.rect = core::rect<s32>(
3406                                         size.X / 2 - 70,       pos.Y,
3407                                         size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3408                         );
3409                         const wchar_t *text = wgettext("Proceed");
3410                         GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3411                         delete[] text;
3412                 }
3413         }
3414
3415         // Set initial focus if parser didn't set it
3416         gui::IGUIElement *focused_element = Environment->getFocus();
3417         if (!focused_element
3418                         || !isMyChild(focused_element)
3419                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3420                 setInitialFocus();
3421
3422         skin->setFont(old_font);
3423
3424         // legacy sorting
3425         if (m_formspec_version < 3)
3426                 legacySortElements(legacy_sort_start);
3427
3428         // Formname and regeneration setting
3429         if (!m_is_form_regenerated) {
3430                 // Only set previous form name if we purposefully showed a new formspec
3431                 m_last_formname = m_text_dst->m_formname;
3432                 m_is_form_regenerated = true;
3433         }
3434 }
3435
3436 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3437 {
3438         /*
3439                 Draw order for formspec_version <= 2:
3440                 -3  bgcolor
3441                 -2  background
3442                 -1  box
3443                 0   All other elements
3444                 1   image
3445                 2   item_image, item_image_button
3446                 3   list
3447                 4   label
3448         */
3449
3450         if (from == Children.end())
3451                 from = Children.begin();
3452         else
3453                 from++;
3454
3455         core::list<IGUIElement *>::Iterator to = Children.end();
3456         // 1: Copy into a sortable container
3457         std::vector<IGUIElement *> elements;
3458         for (auto it = from; it != to; ++it)
3459                 elements.emplace_back(*it);
3460
3461         // 2: Sort the container
3462         std::stable_sort(elements.begin(), elements.end(),
3463                         [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3464                 const FieldSpec *spec_a = getSpecByID(a->getID());
3465                 const FieldSpec *spec_b = getSpecByID(b->getID());
3466                 return spec_a && spec_b &&
3467                         spec_a->priority < spec_b->priority;
3468         });
3469
3470         // 3: Re-assign the pointers
3471         for (auto e : elements) {
3472                 *from = e;
3473                 from++;
3474         }
3475 }
3476
3477 #ifdef __ANDROID__
3478 bool GUIFormSpecMenu::getAndroidUIInput()
3479 {
3480         if (!hasAndroidUIInput())
3481                 return false;
3482
3483         // still waiting
3484         if (porting::getInputDialogState() == -1)
3485                 return true;
3486
3487         std::string fieldname = m_jni_field_name;
3488         m_jni_field_name.clear();
3489
3490         for (const FieldSpec &field : m_fields) {
3491                 if (field.fname != fieldname)
3492                         continue;
3493
3494                 IGUIElement *element = getElementFromId(field.fid, true);
3495
3496                 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3497                         return false;
3498
3499                 std::string text = porting::getInputDialogValue();
3500                 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3501         }
3502         return false;
3503 }
3504 #endif
3505
3506 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3507 {
3508         for (const GUIInventoryList *e : m_inventorylists) {
3509                 s32 item_index = e->getItemIndexAtPos(p);
3510                 if (item_index != -1)
3511                         return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3512                                         item_index);
3513         }
3514
3515         return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3516 }
3517
3518 void GUIFormSpecMenu::drawSelectedItem()
3519 {
3520         video::IVideoDriver* driver = Environment->getVideoDriver();
3521
3522         if (!m_selected_item) {
3523                 // reset rotation time
3524                 drawItemStack(driver, m_font, ItemStack(),
3525                                 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3526                                 m_client, IT_ROT_DRAGGED);
3527                 return;
3528         }
3529
3530         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3531         sanity_check(inv);
3532         InventoryList *list = inv->getList(m_selected_item->listname);
3533         sanity_check(list);
3534         ItemStack stack = list->getItem(m_selected_item->i);
3535         stack.count = m_selected_amount;
3536
3537         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3538         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3539         rect.constrainTo(driver->getViewPort());
3540         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3541 }
3542
3543 void GUIFormSpecMenu::drawMenu()
3544 {
3545         if (m_form_src) {
3546                 const std::string &newform = m_form_src->getForm();
3547                 if (newform != m_formspec_string) {
3548                         m_formspec_string = newform;
3549                         m_is_form_regenerated = false;
3550                         regenerateGui(m_screensize_old);
3551                 }
3552         }
3553
3554         gui::IGUISkin* skin = Environment->getSkin();
3555         sanity_check(skin != NULL);
3556         gui::IGUIFont *old_font = skin->getFont();
3557         skin->setFont(m_font);
3558
3559         m_hovered_item_tooltips.clear();
3560
3561         updateSelectedItem();
3562
3563         video::IVideoDriver* driver = Environment->getVideoDriver();
3564
3565         /*
3566                 Draw background color
3567         */
3568         v2u32 screenSize = driver->getScreenSize();
3569         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3570
3571         if (m_bgfullscreen)
3572                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3573         if (m_bgnonfullscreen)
3574                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3575
3576         /*
3577                 Draw rect_mode tooltip
3578         */
3579         m_tooltip_element->setVisible(false);
3580
3581         for (const auto &pair : m_tooltip_rects) {
3582                 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3583                 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3584                         const std::wstring &text = pair.second.tooltip;
3585                         if (!text.empty()) {
3586                                 showTooltip(text, pair.second.color, pair.second.bgcolor);
3587                                 break;
3588                         }
3589                 }
3590         }
3591
3592         /*
3593                 Draw backgrounds
3594         */
3595         for (gui::IGUIElement *e : m_backgrounds) {
3596                 e->setVisible(true);
3597                 e->draw();
3598                 e->setVisible(false);
3599         }
3600
3601         // Some elements are only visible while being drawn
3602         for (gui::IGUIElement *e : m_clickthrough_elements)
3603                 e->setVisible(true);
3604
3605         /*
3606                 This is where all the drawing happens.
3607         */
3608         core::list<IGUIElement*>::Iterator it = Children.begin();
3609         for (; it != Children.end(); ++it)
3610                 if ((*it)->isNotClipped() ||
3611                                 AbsoluteClippingRect.isRectCollided(
3612                                                 (*it)->getAbsolutePosition()))
3613                         (*it)->draw();
3614
3615         for (gui::IGUIElement *e : m_clickthrough_elements)
3616                 e->setVisible(false);
3617
3618         // Draw hovered item tooltips
3619         for (const std::string &tooltip : m_hovered_item_tooltips) {
3620                 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3621                                 m_default_tooltip_bgcolor);
3622         }
3623
3624         if (m_hovered_item_tooltips.empty()) {
3625                 // reset rotation time
3626                 drawItemStack(driver, m_font, ItemStack(),
3627                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3628                         NULL, m_client, IT_ROT_HOVERED);
3629         }
3630
3631 /* TODO find way to show tooltips on touchscreen */
3632 #ifndef HAVE_TOUCHSCREENGUI
3633         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3634 #endif
3635
3636         /*
3637                 Draw fields/buttons tooltips and update the mouse cursor
3638         */
3639         gui::IGUIElement *hovered =
3640                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3641
3642 #ifndef HAVE_TOUCHSCREENGUI
3643         gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3644                         getCursorControl();
3645         gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3646 #endif
3647         bool hovered_element_found = false;
3648
3649         if (hovered != NULL) {
3650                 if (m_show_debug) {
3651                         core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3652                         driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3653                 }
3654
3655                 s32 id = hovered->getID();
3656                 u64 delta = 0;
3657                 if (id == -1) {
3658                         m_old_tooltip_id = id;
3659                 } else {
3660                         if (id == m_old_tooltip_id) {
3661                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3662                         } else {
3663                                 m_hovered_time = porting::getTimeMs();
3664                                 m_old_tooltip_id = id;
3665                         }
3666                 }
3667
3668                 // Find and update the current tooltip and cursor icon
3669                 if (id != -1) {
3670                         for (const FieldSpec &field : m_fields) {
3671
3672                                 if (field.fid != id)
3673                                         continue;
3674
3675                                 if (delta >= m_tooltip_show_delay) {
3676                                         const std::wstring &text = m_tooltips[field.fname].tooltip;
3677                                         if (!text.empty())
3678                                                 showTooltip(text, m_tooltips[field.fname].color,
3679                                                         m_tooltips[field.fname].bgcolor);
3680                                 }
3681
3682 #ifndef HAVE_TOUCHSCREENGUI
3683                                 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3684                                                 current_cursor_icon != field.fcursor_icon)
3685                                         cursor_control->setActiveIcon(field.fcursor_icon);
3686 #endif
3687
3688                                 hovered_element_found = true;
3689
3690                                 break;
3691                         }
3692                 }
3693         }
3694
3695         if (!hovered_element_found) {
3696                 // no element is hovered
3697 #ifndef HAVE_TOUCHSCREENGUI
3698                 if (current_cursor_icon != ECI_NORMAL)
3699                         cursor_control->setActiveIcon(ECI_NORMAL);
3700 #endif
3701         }
3702
3703         m_tooltip_element->draw();
3704
3705         /*
3706                 Draw dragged item stack
3707         */
3708         drawSelectedItem();
3709
3710         skin->setFont(old_font);
3711 }
3712
3713
3714 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3715         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3716 {
3717         EnrichedString ntext(text);
3718         ntext.setDefaultColor(color);
3719         if (!ntext.hasBackground())
3720                 ntext.setBackground(bgcolor);
3721
3722         setStaticText(m_tooltip_element, ntext);
3723
3724         // Tooltip size and offset
3725         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3726         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3727
3728         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3729         int tooltip_offset_x = m_btn_height;
3730         int tooltip_offset_y = m_btn_height;
3731 #ifdef __ANDROID__
3732         tooltip_offset_x *= 3;
3733         tooltip_offset_y  = 0;
3734         if (m_pointer.X > (s32)screenSize.X / 2)
3735                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3736
3737         // Hide tooltip after ETIE_LEFT_UP
3738         if (m_pointer.X == 0)
3739                 return;
3740 #endif
3741
3742         // Calculate and set the tooltip position
3743         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3744         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3745         if (tooltip_x + tooltip_width > (s32)screenSize.X)
3746                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
3747         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3748                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3749
3750         m_tooltip_element->setRelativePosition(
3751                 core::rect<s32>(
3752                         core::position2d<s32>(tooltip_x, tooltip_y),
3753                         core::dimension2d<s32>(tooltip_width, tooltip_height)
3754                 )
3755         );
3756
3757         // Display the tooltip
3758         m_tooltip_element->setVisible(true);
3759         bringToFront(m_tooltip_element);
3760 }
3761
3762 void GUIFormSpecMenu::updateSelectedItem()
3763 {
3764         verifySelectedItem();
3765
3766         // If craftresult is nonempty and nothing else is selected, select it now.
3767         if (!m_selected_item) {
3768                 for (const GUIInventoryList *e : m_inventorylists) {
3769                         if (e->getListname() != "craftpreview")
3770                                 continue;
3771
3772                         Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3773                         if (!inv)
3774                                 continue;
3775
3776                         InventoryList *list = inv->getList("craftresult");
3777
3778                         if (!list || list->getSize() == 0)
3779                                 continue;
3780
3781                         const ItemStack &item = list->getItem(0);
3782                         if (item.empty())
3783                                 continue;
3784
3785                         // Grab selected item from the crafting result list
3786                         m_selected_item = new GUIInventoryList::ItemSpec;
3787                         m_selected_item->inventoryloc = e->getInventoryloc();
3788                         m_selected_item->listname = "craftresult";
3789                         m_selected_item->i = 0;
3790                         m_selected_amount = item.count;
3791                         m_selected_dragging = false;
3792                         break;
3793                 }
3794         }
3795
3796         // If craftresult is selected, keep the whole stack selected
3797         if (m_selected_item && m_selected_item->listname == "craftresult")
3798                 m_selected_amount = verifySelectedItem().count;
3799 }
3800
3801 ItemStack GUIFormSpecMenu::verifySelectedItem()
3802 {
3803         // If the selected stack has become empty for some reason, deselect it.
3804         // If the selected stack has become inaccessible, deselect it.
3805         // If the selected stack has become smaller, adjust m_selected_amount.
3806         // Return the selected stack.
3807
3808         if (m_selected_item) {
3809                 if (m_selected_item->isValid()) {
3810                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3811                         if (inv) {
3812                                 InventoryList *list = inv->getList(m_selected_item->listname);
3813                                 if (list && (u32) m_selected_item->i < list->getSize()) {
3814                                         ItemStack stack = list->getItem(m_selected_item->i);
3815                                         if (!m_selected_swap.empty()) {
3816                                                 if (m_selected_swap.name == stack.name &&
3817                                                                 m_selected_swap.count == stack.count)
3818                                                         m_selected_swap.clear();
3819                                         } else {
3820                                                 m_selected_amount = std::min(m_selected_amount, stack.count);
3821                                         }
3822
3823                                         if (!stack.empty())
3824                                                 return stack;
3825                                 }
3826                         }
3827                 }
3828
3829                 // selection was not valid
3830                 delete m_selected_item;
3831                 m_selected_item = nullptr;
3832                 m_selected_amount = 0;
3833                 m_selected_dragging = false;
3834         }
3835         return ItemStack();
3836 }
3837
3838 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
3839 {
3840         if(m_text_dst)
3841         {
3842                 StringMap fields;
3843
3844                 if (quitmode == quit_mode_accept) {
3845                         fields["quit"] = "true";
3846                 }
3847
3848                 if (quitmode == quit_mode_cancel) {
3849                         fields["quit"] = "true";
3850                         m_text_dst->gotText(fields);
3851                         return;
3852                 }
3853
3854                 if (current_keys_pending.key_down) {
3855                         fields["key_down"] = "true";
3856                         current_keys_pending.key_down = false;
3857                 }
3858
3859                 if (current_keys_pending.key_up) {
3860                         fields["key_up"] = "true";
3861                         current_keys_pending.key_up = false;
3862                 }
3863
3864                 if (current_keys_pending.key_enter) {
3865                         fields["key_enter"] = "true";
3866                         current_keys_pending.key_enter = false;
3867                 }
3868
3869                 if (!current_field_enter_pending.empty()) {
3870                         fields["key_enter_field"] = current_field_enter_pending;
3871                         current_field_enter_pending = "";
3872                 }
3873
3874                 if (current_keys_pending.key_escape) {
3875                         fields["key_escape"] = "true";
3876                         current_keys_pending.key_escape = false;
3877                 }
3878
3879                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3880                         if (s.send) {
3881                                 std::string name = s.fname;
3882                                 if (s.ftype == f_Button) {
3883                                         fields[name] = wide_to_utf8(s.flabel);
3884                                 } else if (s.ftype == f_Table) {
3885                                         GUITable *table = getTable(s.fname);
3886                                         if (table) {
3887                                                 fields[name] = table->checkEvent();
3888                                         }
3889                                 } else if (s.ftype == f_DropDown) {
3890                                         // No dynamic cast possible due to some distributions shipped
3891                                         // without rtti support in Irrlicht
3892                                         IGUIElement *element = getElementFromId(s.fid, true);
3893                                         gui::IGUIComboBox *e = NULL;
3894                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3895                                                 e = static_cast<gui::IGUIComboBox *>(element);
3896                                         } else {
3897                                                 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3898                                                                 << "field without dropdown element" << std::endl;
3899                                                 continue;
3900                                         }
3901                                         s32 selected = e->getSelected();
3902                                         if (selected >= 0) {
3903                                                 if (m_dropdown_index_event.find(s.fname) !=
3904                                                                 m_dropdown_index_event.end()) {
3905                                                         fields[name] = std::to_string(selected + 1);
3906                                                 } else {
3907                                                         std::vector<std::string> *dropdown_values =
3908                                                                 getDropDownValues(s.fname);
3909                                                         if (dropdown_values && selected < (s32)dropdown_values->size())
3910                                                                 fields[name] = (*dropdown_values)[selected];
3911                                                 }
3912                                         }
3913                                 } else if (s.ftype == f_TabHeader) {
3914                                         // No dynamic cast possible due to some distributions shipped
3915                                         // without rtti support in Irrlicht
3916                                         IGUIElement *element = getElementFromId(s.fid, true);
3917                                         gui::IGUITabControl *e = nullptr;
3918                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3919                                                 e = static_cast<gui::IGUITabControl *>(element);
3920                                         }
3921
3922                                         if (e != 0) {
3923                                                 std::stringstream ss;
3924                                                 ss << (e->getActiveTab() +1);
3925                                                 fields[name] = ss.str();
3926                                         }
3927                                 } else if (s.ftype == f_CheckBox) {
3928                                         // No dynamic cast possible due to some distributions shipped
3929                                         // without rtti support in Irrlicht
3930                                         IGUIElement *element = getElementFromId(s.fid, true);
3931                                         gui::IGUICheckBox *e = nullptr;
3932                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3933                                                 e = static_cast<gui::IGUICheckBox*>(element);
3934                                         }
3935
3936                                         if (e != 0) {
3937                                                 if (e->isChecked())
3938                                                         fields[name] = "true";
3939                                                 else
3940                                                         fields[name] = "false";
3941                                         }
3942                                 } else if (s.ftype == f_ScrollBar) {
3943                                         // No dynamic cast possible due to some distributions shipped
3944                                         // without rtti support in Irrlicht
3945                                         IGUIElement *element = getElementFromId(s.fid, true);
3946                                         GUIScrollBar *e = nullptr;
3947                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3948                                                 e = static_cast<GUIScrollBar *>(element);
3949
3950                                         if (e) {
3951                                                 std::stringstream os;
3952                                                 os << e->getPos();
3953                                                 if (s.fdefault == L"Changed")
3954                                                         fields[name] = "CHG:" + os.str();
3955                                                 else
3956                                                         fields[name] = "VAL:" + os.str();
3957                                         }
3958                                 } else if (s.ftype == f_AnimatedImage) {
3959                                         // No dynamic cast possible due to some distributions shipped
3960                                         // without rtti support in Irrlicht
3961                                         IGUIElement *element = getElementFromId(s.fid, true);
3962                                         GUIAnimatedImage *e = nullptr;
3963                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3964                                                 e = static_cast<GUIAnimatedImage *>(element);
3965
3966                                         if (e)
3967                                                 fields[name] = std::to_string(e->getFrameIndex() + 1);
3968                                 } else {
3969                                         IGUIElement *e = getElementFromId(s.fid, true);
3970                                         if (e)
3971                                                 fields[name] = wide_to_utf8(e->getText());
3972                                 }
3973                         }
3974                 }
3975
3976                 m_text_dst->gotText(fields);
3977         }
3978 }
3979
3980 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3981 {
3982         // The IGUITabControl renders visually using the skin's selected
3983         // font, which we override for the duration of form drawing,
3984         // but computes tab hotspots based on how it would have rendered
3985         // using the font that is selected at the time of button release.
3986         // To make these two consistent, temporarily override the skin's
3987         // font while the IGUITabControl is processing the event.
3988         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3989                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3990                 s32 x = event.MouseInput.X;
3991                 s32 y = event.MouseInput.Y;
3992                 gui::IGUIElement *hovered =
3993                         Environment->getRootGUIElement()->getElementFromPoint(
3994                                 core::position2d<s32>(x, y));
3995                 if (hovered && isMyChild(hovered) &&
3996                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3997                         gui::IGUISkin* skin = Environment->getSkin();
3998                         sanity_check(skin != NULL);
3999                         gui::IGUIFont *old_font = skin->getFont();
4000                         skin->setFont(m_font);
4001                         bool retval = hovered->OnEvent(event);
4002                         skin->setFont(old_font);
4003                         return retval;
4004                 }
4005         }
4006
4007         // Fix Esc/Return key being eaten by checkboxen and tables
4008         if (event.EventType == EET_KEY_INPUT_EVENT) {
4009                         KeyPress kp(event.KeyInput);
4010                 if (kp == EscapeKey || kp == CancelKey
4011                                 || kp == getKeySetting("keymap_inventory")
4012                                 || event.KeyInput.Key==KEY_RETURN) {
4013                         gui::IGUIElement *focused = Environment->getFocus();
4014                         if (focused && isMyChild(focused) &&
4015                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
4016                                         focused->getType() == gui::EGUIET_CHECK_BOX) &&
4017                                         (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
4018                                         event.KeyInput.Key != KEY_RETURN)) {
4019                                 OnEvent(event);
4020                                 return true;
4021                         }
4022                 }
4023         }
4024         // Mouse wheel and move events: send to hovered element instead of focused
4025         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4026                         (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
4027                         (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4028                         event.MouseInput.ButtonStates == 0))) {
4029                 s32 x = event.MouseInput.X;
4030                 s32 y = event.MouseInput.Y;
4031                 gui::IGUIElement *hovered =
4032                         Environment->getRootGUIElement()->getElementFromPoint(
4033                                 core::position2d<s32>(x, y));
4034                 if (hovered && isMyChild(hovered)) {
4035                         hovered->OnEvent(event);
4036                         return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
4037                 }
4038         }
4039
4040         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
4041                 /* TODO add a check like:
4042                 if (event.JoystickEvent != joystick_we_listen_for)
4043                         return false;
4044                 */
4045                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
4046                 if (handled) {
4047                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
4048                                 tryClose();
4049                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
4050                                 if (m_allowclose) {
4051                                         acceptInput(quit_mode_accept);
4052                                         quitMenu();
4053                                 }
4054                         }
4055                 }
4056                 return handled;
4057         }
4058
4059         return GUIModalMenu::preprocessEvent(event);
4060 }
4061
4062 void GUIFormSpecMenu::tryClose()
4063 {
4064         if (m_allowclose) {
4065                 doPause = false;
4066                 acceptInput(quit_mode_cancel);
4067                 quitMenu();
4068         } else {
4069                 m_text_dst->gotText(L"MenuQuit");
4070         }
4071 }
4072
4073 enum ButtonEventType : u8
4074 {
4075         BET_LEFT,
4076         BET_RIGHT,
4077         BET_MIDDLE,
4078         BET_WHEEL_UP,
4079         BET_WHEEL_DOWN,
4080         BET_UP,
4081         BET_DOWN,
4082         BET_MOVE,
4083         BET_OTHER
4084 };
4085
4086 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
4087 {
4088         if (event.EventType==EET_KEY_INPUT_EVENT) {
4089                 KeyPress kp(event.KeyInput);
4090                 if (event.KeyInput.PressedDown && (
4091                                 (kp == EscapeKey) || (kp == CancelKey) ||
4092                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4093                         tryClose();
4094                         return true;
4095                 }
4096
4097                 if (m_client != NULL && event.KeyInput.PressedDown &&
4098                                 (kp == getKeySetting("keymap_screenshot"))) {
4099                         m_client->makeScreenshot();
4100                 }
4101
4102                 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4103                         m_show_debug = !m_show_debug;
4104
4105                 if (event.KeyInput.PressedDown &&
4106                         (event.KeyInput.Key==KEY_RETURN ||
4107                          event.KeyInput.Key==KEY_UP ||
4108                          event.KeyInput.Key==KEY_DOWN)
4109                         ) {
4110                         switch (event.KeyInput.Key) {
4111                                 case KEY_RETURN:
4112                                         current_keys_pending.key_enter = true;
4113                                         break;
4114                                 case KEY_UP:
4115                                         current_keys_pending.key_up = true;
4116                                         break;
4117                                 case KEY_DOWN:
4118                                         current_keys_pending.key_down = true;
4119                                         break;
4120                                 break;
4121                                 default:
4122                                         //can't happen at all!
4123                                         FATAL_ERROR("Reached a source line that can't ever been reached");
4124                                         break;
4125                         }
4126                         if (current_keys_pending.key_enter && m_allowclose) {
4127                                 acceptInput(quit_mode_accept);
4128                                 quitMenu();
4129                         } else {
4130                                 acceptInput();
4131                         }
4132                         return true;
4133                 }
4134
4135         }
4136
4137         /* Mouse event other than movement, or crossing the border of inventory
4138           field while holding right mouse button
4139          */
4140         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4141                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4142                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4143                           event.MouseInput.isRightPressed() &&
4144                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4145
4146                 // Get selected item and hovered/clicked item (s)
4147
4148                 m_old_tooltip_id = -1;
4149                 updateSelectedItem();
4150                 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4151
4152                 Inventory *inv_selected = NULL;
4153                 Inventory *inv_s = NULL;
4154                 InventoryList *list_s = NULL;
4155
4156                 if (m_selected_item) {
4157                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4158                         sanity_check(inv_selected);
4159                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4160                 }
4161
4162                 u32 s_count = 0;
4163
4164                 if (s.isValid())
4165                 do { // breakable
4166                         inv_s = m_invmgr->getInventory(s.inventoryloc);
4167
4168                         if (!inv_s) {
4169                                 errorstream << "InventoryMenu: The selected inventory location "
4170                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4171                                                 << std::endl;
4172                                 s.i = -1;  // make it invalid again
4173                                 break;
4174                         }
4175
4176                         list_s = inv_s->getList(s.listname);
4177                         if (list_s == NULL) {
4178                                 verbosestream << "InventoryMenu: The selected inventory list \""
4179                                                 << s.listname << "\" does not exist" << std::endl;
4180                                 s.i = -1;  // make it invalid again
4181                                 break;
4182                         }
4183
4184                         if ((u32)s.i >= list_s->getSize()) {
4185                                 infostream << "InventoryMenu: The selected inventory list \""
4186                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
4187                                                 << list_s->getSize() << ")" << std::endl;
4188                                 s.i = -1;  // make it invalid again
4189                                 break;
4190                         }
4191
4192                         s_count = list_s->getItem(s.i).count;
4193                 } while(0);
4194
4195                 bool identical = m_selected_item && s.isValid() &&
4196                         (inv_selected == inv_s) &&
4197                         (m_selected_item->listname == s.listname) &&
4198                         (m_selected_item->i == s.i);
4199
4200                 ButtonEventType button = BET_LEFT;
4201                 ButtonEventType updown = BET_OTHER;
4202                 switch (event.MouseInput.Event) {
4203                 case EMIE_LMOUSE_PRESSED_DOWN:
4204                         button = BET_LEFT; updown = BET_DOWN;
4205                         break;
4206                 case EMIE_RMOUSE_PRESSED_DOWN:
4207                         button = BET_RIGHT; updown = BET_DOWN;
4208                         break;
4209                 case EMIE_MMOUSE_PRESSED_DOWN:
4210                         button = BET_MIDDLE; updown = BET_DOWN;
4211                         break;
4212                 case EMIE_MOUSE_WHEEL:
4213                         button = (event.MouseInput.Wheel > 0) ?
4214                                 BET_WHEEL_UP : BET_WHEEL_DOWN;
4215                         updown = BET_DOWN;
4216                         break;
4217                 case EMIE_LMOUSE_LEFT_UP:
4218                         button = BET_LEFT; updown = BET_UP;
4219                         break;
4220                 case EMIE_RMOUSE_LEFT_UP:
4221                         button = BET_RIGHT; updown = BET_UP;
4222                         break;
4223                 case EMIE_MMOUSE_LEFT_UP:
4224                         button = BET_MIDDLE; updown = BET_UP;
4225                         break;
4226                 case EMIE_MOUSE_MOVED:
4227                         updown = BET_MOVE;
4228                         break;
4229                 default:
4230                         break;
4231                 }
4232
4233                 // Set this number to a positive value to generate a move action
4234                 // from m_selected_item to s.
4235                 u32 move_amount = 0;
4236
4237                 // Set this number to a positive value to generate a move action
4238                 // from s to the next inventory ring.
4239                 u32 shift_move_amount = 0;
4240
4241                 // Set this number to a positive value to generate a drop action
4242                 // from m_selected_item.
4243                 u32 drop_amount = 0;
4244
4245                 // Set this number to a positive value to generate a craft action at s.
4246                 u32 craft_amount = 0;
4247
4248                 switch (updown) {
4249                 case BET_DOWN:
4250                         // Some mouse button has been pressed
4251
4252                         //infostream << "Mouse button " << button << " pressed at p=("
4253                         //      << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4254                         //      << std::endl;
4255
4256                         m_selected_dragging = false;
4257
4258                         if (s.isValid() && s.listname == "craftpreview") {
4259                                 // Craft preview has been clicked: craft
4260                                 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4261                         } else if (!m_selected_item) {
4262                                 if (s_count && button != BET_WHEEL_UP) {
4263                                         // Non-empty stack has been clicked: select or shift-move it
4264                                         m_selected_item = new GUIInventoryList::ItemSpec(s);
4265
4266                                         u32 count;
4267                                         if (button == BET_RIGHT)
4268                                                 count = (s_count + 1) / 2;
4269                                         else if (button == BET_MIDDLE)
4270                                                 count = MYMIN(s_count, 10);
4271                                         else if (button == BET_WHEEL_DOWN)
4272                                                 count = 1;
4273                                         else  // left
4274                                                 count = s_count;
4275
4276                                         if (!event.MouseInput.Shift) {
4277                                                 // no shift: select item
4278                                                 m_selected_amount = count;
4279                                                 m_selected_dragging = button != BET_WHEEL_DOWN;
4280                                                 m_auto_place = false;
4281                                         } else {
4282                                                 // shift pressed: move item, right click moves 1
4283                                                 shift_move_amount = button == BET_RIGHT ? 1 : count;
4284                                         }
4285                                 }
4286                         } else { // m_selected_item != NULL
4287                                 assert(m_selected_amount >= 1);
4288
4289                                 if (s.isValid()) {
4290                                         // Clicked a slot: move
4291                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4292                                                 move_amount = 1;
4293                                         else if (button == BET_MIDDLE)
4294                                                 move_amount = MYMIN(m_selected_amount, 10);
4295                                         else if (button == BET_LEFT)
4296                                                 move_amount = m_selected_amount;
4297                                         // else wheeldown
4298
4299                                         if (identical) {
4300                                                 if (button == BET_WHEEL_DOWN) {
4301                                                         if (m_selected_amount < s_count)
4302                                                                 ++m_selected_amount;
4303                                                 } else {
4304                                                         if (move_amount >= m_selected_amount)
4305                                                                 m_selected_amount = 0;
4306                                                         else
4307                                                                 m_selected_amount -= move_amount;
4308                                                         move_amount = 0;
4309                                                 }
4310                                         }
4311                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4312                                                 && button != BET_WHEEL_DOWN) {
4313                                         // Clicked outside of the window: drop
4314                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4315                                                 drop_amount = 1;
4316                                         else if (button == BET_MIDDLE)
4317                                                 drop_amount = MYMIN(m_selected_amount, 10);
4318                                         else  // left
4319                                                 drop_amount = m_selected_amount;
4320                                 }
4321                         }
4322                 break;
4323                 case BET_UP:
4324                         // Some mouse button has been released
4325
4326                         //infostream<<"Mouse button "<<button<<" released at p=("
4327                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
4328
4329                         if (m_selected_dragging && m_selected_item) {
4330                                 if (s.isValid()) {
4331                                         if (!identical) {
4332                                                 // Dragged to different slot: move all selected
4333                                                 move_amount = m_selected_amount;
4334                                         }
4335                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4336                                         // Dragged outside of window: drop all selected
4337                                         drop_amount = m_selected_amount;
4338                                 }
4339                         }
4340
4341                         m_selected_dragging = false;
4342                         // Keep track of whether the mouse button be released
4343                         // One click is drag without dropping. Click + release
4344                         // + click changes to drop item when moved mode
4345                         if (m_selected_item)
4346                                 m_auto_place = true;
4347                 break;
4348                 case BET_MOVE:
4349                         // Mouse has been moved and rmb is down and mouse pointer just
4350                         // entered a new inventory field (checked in the entry-if, this
4351                         // is the only action here that is generated by mouse movement)
4352                         if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4353                                 // Move 1 item
4354                                 // TODO: middle mouse to move 10 items might be handy
4355                                 if (m_auto_place) {
4356                                         // Only move an item if the destination slot is empty
4357                                         // or contains the same item type as what is going to be
4358                                         // moved
4359                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4360                                         InventoryList *list_to = list_s;
4361                                         assert(list_from && list_to);
4362                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4363                                         ItemStack stack_to = list_to->getItem(s.i);
4364                                         if (stack_to.empty() || stack_to.name == stack_from.name)
4365                                                 move_amount = 1;
4366                                 }
4367                         }
4368                 break;
4369                 default:
4370                         break;
4371                 }
4372
4373                 // Possibly send inventory action to server
4374                 if (move_amount > 0) {
4375                         // Send IAction::Move
4376
4377                         assert(m_selected_item && m_selected_item->isValid());
4378                         assert(s.isValid());
4379
4380                         assert(inv_selected && inv_s);
4381                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4382                         InventoryList *list_to = list_s;
4383                         assert(list_from && list_to);
4384                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4385                         ItemStack stack_to = list_to->getItem(s.i);
4386
4387                         // Check how many items can be moved
4388                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4389                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4390                         bool move = true;
4391                         // If source stack cannot be added to destination stack at all,
4392                         // they are swapped
4393                         if (leftover.count == stack_from.count &&
4394                                         leftover.name == stack_from.name) {
4395
4396                                 if (m_selected_swap.empty()) {
4397                                         m_selected_amount = stack_to.count;
4398                                         m_selected_dragging = false;
4399
4400                                         // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4401                                         // Skip next validation checks due async inventory calls
4402                                         m_selected_swap = stack_to;
4403                                 } else {
4404                                         move = false;
4405                                 }
4406                         }
4407                         // Source stack goes fully into destination stack
4408                         else if (leftover.empty()) {
4409                                 m_selected_amount -= move_amount;
4410                         }
4411                         // Source stack goes partly into destination stack
4412                         else {
4413                                 move_amount -= leftover.count;
4414                                 m_selected_amount -= move_amount;
4415                         }
4416
4417                         if (move) {
4418                                 infostream << "Handing IAction::Move to manager" << std::endl;
4419                                 IMoveAction *a = new IMoveAction();
4420                                 a->count = move_amount;
4421                                 a->from_inv = m_selected_item->inventoryloc;
4422                                 a->from_list = m_selected_item->listname;
4423                                 a->from_i = m_selected_item->i;
4424                                 a->to_inv = s.inventoryloc;
4425                                 a->to_list = s.listname;
4426                                 a->to_i = s.i;
4427                                 m_invmgr->inventoryAction(a);
4428                         }
4429                 } else if (shift_move_amount > 0) {
4430                         u32 mis = m_inventory_rings.size();
4431                         u32 i = 0;
4432                         for (; i < mis; i++) {
4433                                 const ListRingSpec &sp = m_inventory_rings[i];
4434                                 if (sp.inventoryloc == s.inventoryloc
4435                                                 && sp.listname == s.listname)
4436                                         break;
4437                         }
4438                         do {
4439                                 if (i >= mis) // if not found
4440                                         break;
4441                                 u32 to_inv_ind = (i + 1) % mis;
4442                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4443                                 InventoryList *list_from = list_s;
4444                                 if (!s.isValid())
4445                                         break;
4446                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4447                                 if (!inv_to)
4448                                         break;
4449                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4450                                 if (!list_to)
4451                                         break;
4452                                 ItemStack stack_from = list_from->getItem(s.i);
4453                                 assert(shift_move_amount <= stack_from.count);
4454
4455                                 infostream << "Handing IAction::Move to manager" << std::endl;
4456                                 IMoveAction *a = new IMoveAction();
4457                                 a->count = shift_move_amount;
4458                                 a->from_inv = s.inventoryloc;
4459                                 a->from_list = s.listname;
4460                                 a->from_i = s.i;
4461                                 a->to_inv = to_inv_sp.inventoryloc;
4462                                 a->to_list = to_inv_sp.listname;
4463                                 a->move_somewhere = true;
4464                                 m_invmgr->inventoryAction(a);
4465                         } while (0);
4466                 } else if (drop_amount > 0) {
4467                         // Send IAction::Drop
4468
4469                         assert(m_selected_item && m_selected_item->isValid());
4470                         assert(inv_selected);
4471                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4472                         assert(list_from);
4473                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4474
4475                         // Check how many items can be dropped
4476                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4477                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4478                         m_selected_amount -= drop_amount;
4479
4480                         infostream << "Handing IAction::Drop to manager" << std::endl;
4481                         IDropAction *a = new IDropAction();
4482                         a->count = drop_amount;
4483                         a->from_inv = m_selected_item->inventoryloc;
4484                         a->from_list = m_selected_item->listname;
4485                         a->from_i = m_selected_item->i;
4486                         m_invmgr->inventoryAction(a);
4487                 } else if (craft_amount > 0) {
4488                         assert(s.isValid());
4489
4490                         // if there are no items selected or the selected item
4491                         // belongs to craftresult list, proceed with crafting
4492                         if (!m_selected_item ||
4493                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4494
4495                                 assert(inv_s);
4496
4497                                 // Send IACTION_CRAFT
4498                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4499                                 ICraftAction *a = new ICraftAction();
4500                                 a->count = craft_amount;
4501                                 a->craft_inv = s.inventoryloc;
4502                                 m_invmgr->inventoryAction(a);
4503                         }
4504                 }
4505
4506                 // If m_selected_amount has been decreased to zero, deselect
4507                 if (m_selected_amount == 0) {
4508                         m_selected_swap.clear();
4509                         delete m_selected_item;
4510                         m_selected_item = nullptr;
4511                         m_selected_amount = 0;
4512                         m_selected_dragging = false;
4513                 }
4514                 m_old_pointer = m_pointer;
4515         }
4516
4517         if (event.EventType == EET_GUI_EVENT) {
4518                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4519                                 && isVisible()) {
4520                         // find the element that was clicked
4521                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4522                                 if ((s.ftype == f_TabHeader) &&
4523                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4524                                         if (!s.sound.empty() && m_sound_manager)
4525                                                 m_sound_manager->playSound(s.sound, false, 1.0f);
4526                                         s.send = true;
4527                                         acceptInput();
4528                                         s.send = false;
4529                                         return true;
4530                                 }
4531                         }
4532                 }
4533                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4534                                 && isVisible()) {
4535                         if (!canTakeFocus(event.GUIEvent.Element)) {
4536                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4537                                                 <<std::endl;
4538                                 // Returning true disables focus change
4539                                 return true;
4540                         }
4541                 }
4542                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4543                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4544                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4545                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4546                         s32 caller_id = event.GUIEvent.Caller->getID();
4547
4548                         if (caller_id == 257) {
4549                                 if (m_allowclose) {
4550                                         acceptInput(quit_mode_accept);
4551                                         quitMenu();
4552                                 } else {
4553                                         acceptInput();
4554                                         m_text_dst->gotText(L"ExitButton");
4555                                 }
4556                                 // quitMenu deallocates menu
4557                                 return true;
4558                         }
4559
4560                         // find the element that was clicked
4561                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4562                                 // if its a button, set the send field so
4563                                 // lua knows which button was pressed
4564
4565                                 if (caller_id != s.fid)
4566                                         continue;
4567
4568                                 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4569                                         if (!s.sound.empty() && m_sound_manager)
4570                                                 m_sound_manager->playSound(s.sound, false, 1.0f);
4571
4572                                         s.send = true;
4573                                         if (s.is_exit) {
4574                                                 if (m_allowclose) {
4575                                                         acceptInput(quit_mode_accept);
4576                                                         quitMenu();
4577                                                 } else {
4578                                                         m_text_dst->gotText(L"ExitButton");
4579                                                 }
4580                                                 return true;
4581                                         }
4582
4583                                         acceptInput(quit_mode_no);
4584                                         s.send = false;
4585                                         return true;
4586
4587                                 } else if (s.ftype == f_DropDown) {
4588                                         // only send the changed dropdown
4589                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4590                                                 if (s2.ftype == f_DropDown) {
4591                                                         s2.send = false;
4592                                                 }
4593                                         }
4594                                         if (!s.sound.empty() && m_sound_manager)
4595                                                 m_sound_manager->playSound(s.sound, false, 1.0f);
4596                                         s.send = true;
4597                                         acceptInput(quit_mode_no);
4598
4599                                         // revert configuration to make sure dropdowns are sent on
4600                                         // regular button click
4601                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4602                                                 if (s2.ftype == f_DropDown) {
4603                                                         s2.send = true;
4604                                                 }
4605                                         }
4606                                         return true;
4607                                 } else if (s.ftype == f_ScrollBar) {
4608                                         s.fdefault = L"Changed";
4609                                         acceptInput(quit_mode_no);
4610                                         s.fdefault = L"";
4611                                 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4612                                         if (!s.sound.empty() && m_sound_manager)
4613                                                 m_sound_manager->playSound(s.sound, false, 1.0f);
4614                                         s.send = true;
4615                                         acceptInput();
4616                                         s.send = false;
4617                                 }
4618                         }
4619                 }
4620
4621                 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4622                         // move scroll_containers
4623                         for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4624                                 c.second->onScrollEvent(event.GUIEvent.Caller);
4625                 }
4626
4627                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4628                         if (event.GUIEvent.Caller->getID() > 257) {
4629                                 bool close_on_enter = true;
4630                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4631                                         if (s.ftype == f_Unknown &&
4632                                                         s.fid == event.GUIEvent.Caller->getID()) {
4633                                                 current_field_enter_pending = s.fname;
4634                                                 std::unordered_map<std::string, bool>::const_iterator it =
4635                                                         field_close_on_enter.find(s.fname);
4636                                                 if (it != field_close_on_enter.end())
4637                                                         close_on_enter = (*it).second;
4638
4639                                                 break;
4640                                         }
4641                                 }
4642
4643                                 if (m_allowclose && close_on_enter) {
4644                                         current_keys_pending.key_enter = true;
4645                                         acceptInput(quit_mode_accept);
4646                                         quitMenu();
4647                                 } else {
4648                                         current_keys_pending.key_enter = true;
4649                                         acceptInput();
4650                                 }
4651                                 // quitMenu deallocates menu
4652                                 return true;
4653                         }
4654                 }
4655
4656                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4657                         int current_id = event.GUIEvent.Caller->getID();
4658                         if (current_id > 257) {
4659                                 // find the element that was clicked
4660                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4661                                         // if it's a table, set the send field
4662                                         // so lua knows which table was changed
4663                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
4664                                                 s.send = true;
4665                                                 acceptInput();
4666                                                 s.send=false;
4667                                         }
4668                                 }
4669                                 return true;
4670                         }
4671                 }
4672         }
4673
4674         return Parent ? Parent->OnEvent(event) : false;
4675 }
4676
4677 /**
4678  * get name of element by element id
4679  * @param id of element
4680  * @return name string or empty string
4681  */
4682 std::string GUIFormSpecMenu::getNameByID(s32 id)
4683 {
4684         for (FieldSpec &spec : m_fields) {
4685                 if (spec.fid == id)
4686                         return spec.fname;
4687         }
4688         return "";
4689 }
4690
4691
4692 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4693 {
4694         for (FieldSpec &spec : m_fields) {
4695                 if (spec.fid == id)
4696                         return &spec;
4697         }
4698         return nullptr;
4699 }
4700
4701 /**
4702  * get label of element by id
4703  * @param id of element
4704  * @return label string or empty string
4705  */
4706 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4707 {
4708         for (FieldSpec &spec : m_fields) {
4709                 if (spec.fid == id)
4710                         return spec.flabel;
4711         }
4712         return L"";
4713 }
4714
4715 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4716                 const std::string &name, const std::string &parent_type) {
4717         return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4718 }
4719
4720 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4721         const std::string &type, const std::string &name, const std::string &parent_type)
4722 {
4723         std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4724
4725         auto it = theme_by_type.find("*");
4726         if (it != theme_by_type.end()) {
4727                 for (const StyleSpec &spec : it->second)
4728                         ret[(u32)spec.getState()] |= spec;
4729         }
4730
4731         it = theme_by_name.find("*");
4732         if (it != theme_by_name.end()) {
4733                 for (const StyleSpec &spec : it->second)
4734                         ret[(u32)spec.getState()] |= spec;
4735         }
4736
4737         if (!parent_type.empty()) {
4738                 it = theme_by_type.find(parent_type);
4739                 if (it != theme_by_type.end()) {
4740                         for (const StyleSpec &spec : it->second)
4741                                 ret[(u32)spec.getState()] |= spec;
4742                 }
4743         }
4744
4745         it = theme_by_type.find(type);
4746         if (it != theme_by_type.end()) {
4747                 for (const StyleSpec &spec : it->second)
4748                         ret[(u32)spec.getState()] |= spec;
4749         }
4750
4751         it = theme_by_name.find(name);
4752         if (it != theme_by_name.end()) {
4753                 for (const StyleSpec &spec : it->second)
4754                         ret[(u32)spec.getState()] |= spec;
4755         }
4756
4757         return ret;
4758 }