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