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