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