Add animated_image[] formspec element (#9258)
[oweals/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                 log_deprecated("Deprecated formspec element \"invsize\" is used");
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         std::string selector = trim(parts[0]);
2454         if (selector.empty()) {
2455                 errorstream << "Invalid style element (Selector required): '" << element
2456                                         << "'" << std::endl;
2457                 return false;
2458         }
2459
2460         StyleSpec spec;
2461
2462         for (size_t i = 1; i < parts.size(); i++) {
2463                 size_t equal_pos = parts[i].find('=');
2464                 if (equal_pos == std::string::npos) {
2465                         errorstream << "Invalid style element (Property missing value): '" << element
2466                                                 << "'" << std::endl;
2467                         return false;
2468                 }
2469
2470                 std::string propname = trim(parts[i].substr(0, equal_pos));
2471                 std::string value    = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2472
2473                 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2474
2475                 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2476                 if (prop == StyleSpec::NONE) {
2477                         if (property_warned.find(propname) != property_warned.end()) {
2478                                 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2479                                                 << element
2480                                                 << "'" << std::endl;
2481                                 property_warned.insert(propname);
2482                         }
2483                         return false;
2484                 }
2485
2486                 spec.set(prop, value);
2487         }
2488
2489         if (style_type) {
2490                 theme_by_type[selector] |= spec;
2491         } else {
2492                 theme_by_name[selector] |= spec;
2493         }
2494
2495         return true;
2496 }
2497
2498 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2499 {
2500         //some prechecks
2501         if (element.empty())
2502                 return;
2503
2504         if (parseVersionDirect(element))
2505                 return;
2506
2507         std::vector<std::string> parts = split(element,'[');
2508
2509         // ugly workaround to keep compatibility
2510         if (parts.size() > 2) {
2511                 if (trim(parts[0]) == "image") {
2512                         for (unsigned int i=2;i< parts.size(); i++) {
2513                                 parts[1] += "[" + parts[i];
2514                         }
2515                 }
2516                 else { return; }
2517         }
2518
2519         if (parts.size() < 2) {
2520                 return;
2521         }
2522
2523         std::string type = trim(parts[0]);
2524         std::string description = trim(parts[1]);
2525
2526         if (type == "container") {
2527                 parseContainer(data, description);
2528                 return;
2529         }
2530
2531         if (type == "container_end") {
2532                 parseContainerEnd(data);
2533                 return;
2534         }
2535
2536         if (type == "list") {
2537                 parseList(data, description);
2538                 return;
2539         }
2540
2541         if (type == "listring") {
2542                 parseListRing(data, description);
2543                 return;
2544         }
2545
2546         if (type == "checkbox") {
2547                 parseCheckbox(data, description);
2548                 return;
2549         }
2550
2551         if (type == "image") {
2552                 parseImage(data, description);
2553                 return;
2554         }
2555
2556         if (type == "animated_image") {
2557                 parseAnimatedImage(data, description);
2558                 return;
2559         }
2560
2561         if (type == "item_image") {
2562                 parseItemImage(data, description);
2563                 return;
2564         }
2565
2566         if (type == "button" || type == "button_exit") {
2567                 parseButton(data, description, type);
2568                 return;
2569         }
2570
2571         if (type == "background" || type == "background9") {
2572                 parseBackground(data, description);
2573                 return;
2574         }
2575
2576         if (type == "tableoptions"){
2577                 parseTableOptions(data,description);
2578                 return;
2579         }
2580
2581         if (type == "tablecolumns"){
2582                 parseTableColumns(data,description);
2583                 return;
2584         }
2585
2586         if (type == "table"){
2587                 parseTable(data,description);
2588                 return;
2589         }
2590
2591         if (type == "textlist"){
2592                 parseTextList(data,description);
2593                 return;
2594         }
2595
2596         if (type == "dropdown"){
2597                 parseDropDown(data,description);
2598                 return;
2599         }
2600
2601         if (type == "field_close_on_enter") {
2602                 parseFieldCloseOnEnter(data, description);
2603                 return;
2604         }
2605
2606         if (type == "pwdfield") {
2607                 parsePwdField(data,description);
2608                 return;
2609         }
2610
2611         if ((type == "field") || (type == "textarea")){
2612                 parseField(data,description,type);
2613                 return;
2614         }
2615
2616         if (type == "hypertext") {
2617                 parseHyperText(data,description);
2618                 return;
2619         }
2620
2621         if (type == "label") {
2622                 parseLabel(data,description);
2623                 return;
2624         }
2625
2626         if (type == "vertlabel") {
2627                 parseVertLabel(data,description);
2628                 return;
2629         }
2630
2631         if (type == "item_image_button") {
2632                 parseItemImageButton(data,description);
2633                 return;
2634         }
2635
2636         if ((type == "image_button") || (type == "image_button_exit")) {
2637                 parseImageButton(data,description,type);
2638                 return;
2639         }
2640
2641         if (type == "tabheader") {
2642                 parseTabHeader(data,description);
2643                 return;
2644         }
2645
2646         if (type == "box") {
2647                 parseBox(data,description);
2648                 return;
2649         }
2650
2651         if (type == "bgcolor") {
2652                 parseBackgroundColor(data,description);
2653                 return;
2654         }
2655
2656         if (type == "listcolors") {
2657                 parseListColors(data,description);
2658                 return;
2659         }
2660
2661         if (type == "tooltip") {
2662                 parseTooltip(data,description);
2663                 return;
2664         }
2665
2666         if (type == "scrollbar") {
2667                 parseScrollBar(data, description);
2668                 return;
2669         }
2670
2671         if (type == "real_coordinates") {
2672                 data->real_coordinates = is_yes(description);
2673                 return;
2674         }
2675
2676         if (type == "style") {
2677                 parseStyle(data, description, false);
2678                 return;
2679         }
2680
2681         if (type == "style_type") {
2682                 parseStyle(data, description, true);
2683                 return;
2684         }
2685
2686         if (type == "scrollbaroptions") {
2687                 parseScrollBarOptions(data, description);
2688                 return;
2689         }
2690
2691         // Ignore others
2692         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2693                         << std::endl;
2694 }
2695
2696 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2697 {
2698         /* useless to regenerate without a screensize */
2699         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2700                 return;
2701         }
2702
2703         parserData mydata;
2704
2705         //preserve tables
2706         for (auto &m_table : m_tables) {
2707                 std::string tablename = m_table.first.fname;
2708                 GUITable *table = m_table.second;
2709                 mydata.table_dyndata[tablename] = table->getDynamicData();
2710         }
2711
2712         //set focus
2713         if (!m_focused_element.empty())
2714                 mydata.focused_fieldname = m_focused_element;
2715
2716         //preserve focus
2717         gui::IGUIElement *focused_element = Environment->getFocus();
2718         if (focused_element && focused_element->getParent() == this) {
2719                 s32 focused_id = focused_element->getID();
2720                 if (focused_id > 257) {
2721                         for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2722                                 if (field.fid == focused_id) {
2723                                         mydata.focused_fieldname = field.fname;
2724                                         break;
2725                                 }
2726                         }
2727                 }
2728         }
2729
2730         // Remove children
2731         removeChildren();
2732
2733         for (auto &table_it : m_tables)
2734                 table_it.second->drop();
2735         for (auto &inventorylist_it : m_inventorylists)
2736                 inventorylist_it->drop();
2737         for (auto &checkbox_it : m_checkboxes)
2738                 checkbox_it.second->drop();
2739         for (auto &scrollbar_it : m_scrollbars)
2740                 scrollbar_it.second->drop();
2741         for (auto &background_it : m_backgrounds)
2742                 background_it->drop();
2743         for (auto &tooltip_rect_it : m_tooltip_rects)
2744                 tooltip_rect_it.first->drop();
2745
2746         mydata.size= v2s32(100,100);
2747         mydata.screensize = screensize;
2748         mydata.offset = v2f32(0.5f, 0.5f);
2749         mydata.anchor = v2f32(0.5f, 0.5f);
2750         mydata.simple_field_count = 0;
2751
2752         // Base position of contents of form
2753         mydata.basepos = getBasePos();
2754
2755         m_inventorylists.clear();
2756         m_backgrounds.clear();
2757         m_tables.clear();
2758         m_checkboxes.clear();
2759         m_scrollbars.clear();
2760         m_fields.clear();
2761         m_tooltips.clear();
2762         m_tooltip_rects.clear();
2763         m_inventory_rings.clear();
2764         m_dropdowns.clear();
2765         theme_by_name.clear();
2766         theme_by_type.clear();
2767
2768         m_bgnonfullscreen = true;
2769         m_bgfullscreen = false;
2770
2771         m_formspec_version = 1;
2772
2773         {
2774                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2775                 m_bgcolor = video::SColor(
2776                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2777                         clamp_u8(myround(formspec_bgcolor.X)),
2778                         clamp_u8(myround(formspec_bgcolor.Y)),
2779                         clamp_u8(myround(formspec_bgcolor.Z))
2780                 );
2781         }
2782
2783         {
2784                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2785                 m_fullscreen_bgcolor = video::SColor(
2786                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2787                         clamp_u8(myround(formspec_bgcolor.X)),
2788                         clamp_u8(myround(formspec_bgcolor.Y)),
2789                         clamp_u8(myround(formspec_bgcolor.Z))
2790                 );
2791         }
2792
2793         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2794         m_default_tooltip_color = video::SColor(255,255,255,255);
2795
2796         // Add tooltip
2797         {
2798                 assert(!m_tooltip_element);
2799                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2800                 m_tooltip_element = gui::StaticText::add(Environment, L"",
2801                         core::rect<s32>(0, 0, 110, 18));
2802                 m_tooltip_element->enableOverrideColor(true);
2803                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2804                 m_tooltip_element->setDrawBackground(true);
2805                 m_tooltip_element->setDrawBorder(true);
2806                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2807                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2808                 m_tooltip_element->setWordWrap(false);
2809                 //we're not parent so no autograb for this one!
2810                 m_tooltip_element->grab();
2811         }
2812
2813         std::vector<std::string> elements = split(m_formspec_string,']');
2814         unsigned int i = 0;
2815
2816         /* try to read version from first element only */
2817         if (!elements.empty()) {
2818                 if (parseVersionDirect(elements[0])) {
2819                         i++;
2820                 }
2821         }
2822
2823         /* we need size first in order to calculate image scale */
2824         mydata.explicit_size = false;
2825         for (; i< elements.size(); i++) {
2826                 if (!parseSizeDirect(&mydata, elements[i])) {
2827                         break;
2828                 }
2829         }
2830
2831         /* "position" element is always after "size" element if it used */
2832         for (; i< elements.size(); i++) {
2833                 if (!parsePositionDirect(&mydata, elements[i])) {
2834                         break;
2835                 }
2836         }
2837
2838         /* "anchor" element is always after "position" (or  "size" element) if it used */
2839         for (; i< elements.size(); i++) {
2840                 if (!parseAnchorDirect(&mydata, elements[i])) {
2841                         break;
2842                 }
2843         }
2844
2845         /* "no_prepend" element is always after "position" (or  "size" element) if it used */
2846         bool enable_prepends = true;
2847         for (; i < elements.size(); i++) {
2848                 if (elements[i].empty())
2849                         break;
2850
2851                 std::vector<std::string> parts = split(elements[i], '[');
2852                 if (trim(parts[0]) == "no_prepend")
2853                         enable_prepends = false;
2854                 else
2855                         break;
2856         }
2857
2858         /* Copy of the "real_coordinates" element for after the form size. */
2859         mydata.real_coordinates = m_formspec_version >= 2;
2860         for (; i < elements.size(); i++) {
2861                 std::vector<std::string> parts = split(elements[i], '[');
2862                 std::string name = trim(parts[0]);
2863                 if (name != "real_coordinates" || parts.size() != 2)
2864                         break; // Invalid format
2865
2866                 mydata.real_coordinates = is_yes(trim(parts[1]));
2867         }
2868
2869         if (mydata.explicit_size) {
2870                 // compute scaling for specified form size
2871                 if (m_lock) {
2872                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2873                         v2u32 delta = current_screensize - m_lockscreensize;
2874
2875                         if (current_screensize.Y > m_lockscreensize.Y)
2876                                 delta.Y /= 2;
2877                         else
2878                                 delta.Y = 0;
2879
2880                         if (current_screensize.X > m_lockscreensize.X)
2881                                 delta.X /= 2;
2882                         else
2883                                 delta.X = 0;
2884
2885                         offset = v2s32(delta.X,delta.Y);
2886
2887                         mydata.screensize = m_lockscreensize;
2888                 } else {
2889                         offset = v2s32(0,0);
2890                 }
2891
2892                 double gui_scaling = g_settings->getFloat("gui_scaling");
2893                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2894
2895                 double use_imgsize;
2896                 if (m_lock) {
2897                         // In fixed-size mode, inventory image size
2898                         // is 0.53 inch multiplied by the gui_scaling
2899                         // config parameter.  This magic size is chosen
2900                         // to make the main menu (15.5 inventory images
2901                         // wide, including border) just fit into the
2902                         // default window (800 pixels wide) at 96 DPI
2903                         // and default scaling (1.00).
2904                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2905                 } else {
2906                         // In variable-size mode, we prefer to make the
2907                         // inventory image size 1/15 of screen height,
2908                         // multiplied by the gui_scaling config parameter.
2909                         // If the preferred size won't fit the whole
2910                         // form on the screen, either horizontally or
2911                         // vertically, then we scale it down to fit.
2912                         // (The magic numbers in the computation of what
2913                         // fits arise from the scaling factors in the
2914                         // following stanza, including the form border,
2915                         // help text space, and 0.1 inventory slot spare.)
2916                         // However, a minimum size is also set, that
2917                         // the image size can't be less than 0.3 inch
2918                         // multiplied by gui_scaling, even if this means
2919                         // the form doesn't fit the screen.
2920 #ifdef __ANDROID__
2921                         // For mobile devices these magic numbers are
2922                         // different and forms should always use the
2923                         // maximum screen space available.
2924                         double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
2925                         double fitx_imgsize = mydata.screensize.X /
2926                                 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
2927                         double fity_imgsize = mydata.screensize.Y /
2928                                 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
2929                         use_imgsize = MYMIN(prefer_imgsize,
2930                                         MYMIN(fitx_imgsize, fity_imgsize));
2931 #else
2932                         double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
2933                         double fitx_imgsize = mydata.screensize.X /
2934                                 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
2935                         double fity_imgsize = mydata.screensize.Y /
2936                                 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
2937                         double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2938                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2939                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2940                                 MYMIN(fitx_imgsize, fity_imgsize)));
2941 #endif
2942                 }
2943
2944                 // Everything else is scaled in proportion to the
2945                 // inventory image size.  The inventory slot spacing
2946                 // is 5/4 image size horizontally and 15/13 image size
2947                 // vertically.  The padding around the form (incorporating
2948                 // the border of the outer inventory slots) is 3/8
2949                 // image size.  Font height (baseline to baseline)
2950                 // is 2/5 vertical inventory slot spacing, and button
2951                 // half-height is 7/8 of font height.
2952                 imgsize = v2s32(use_imgsize, use_imgsize);
2953                 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2954                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2955                 m_btn_height = use_imgsize*15.0/13 * 0.35;
2956
2957                 m_font = g_fontengine->getFont();
2958
2959                 if (mydata.real_coordinates) {
2960                         mydata.size = v2s32(
2961                                 mydata.invsize.X*imgsize.X,
2962                                 mydata.invsize.Y*imgsize.Y
2963                         );
2964                 } else {
2965                         mydata.size = v2s32(
2966                                 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2967                                 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2968                         );
2969                 }
2970
2971                 DesiredRect = mydata.rect = core::rect<s32>(
2972                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2973                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2974                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2975                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2976                 );
2977         } else {
2978                 // Non-size[] form must consist only of text fields and
2979                 // implicit "Proceed" button.  Use default font, and
2980                 // temporary form size which will be recalculated below.
2981                 m_font = g_fontengine->getFont();
2982                 m_btn_height = font_line_height(m_font) * 0.875;
2983                 DesiredRect = core::rect<s32>(
2984                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2985                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2986                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2987                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2988                 );
2989         }
2990         recalculateAbsolutePosition(false);
2991         mydata.basepos = getBasePos();
2992         m_tooltip_element->setOverrideFont(m_font);
2993
2994         gui::IGUISkin *skin = Environment->getSkin();
2995         sanity_check(skin);
2996         gui::IGUIFont *old_font = skin->getFont();
2997         skin->setFont(m_font);
2998
2999         pos_offset = v2f32();
3000
3001         // used for formspec versions < 3
3002         core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3003
3004         if (enable_prepends) {
3005                 // Backup the coordinates so that prepends can use the coordinates of choice.
3006                 bool rc_backup = mydata.real_coordinates;
3007                 u16 version_backup = m_formspec_version;
3008                 mydata.real_coordinates = false; // Old coordinates by default.
3009
3010                 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3011                 for (const auto &element : prepend_elements)
3012                         parseElement(&mydata, element);
3013
3014                 // legacy sorting for formspec versions < 3
3015                 if (m_formspec_version >= 3)
3016                         // prepends do not need to be reordered
3017                         legacy_sort_start = Children.getLast();
3018                 else if (version_backup >= 3)
3019                         // only prepends elements have to be reordered
3020                         legacySortElements(legacy_sort_start);
3021
3022                 m_formspec_version = version_backup;
3023                 mydata.real_coordinates = rc_backup; // Restore coordinates
3024         }
3025
3026         for (; i< elements.size(); i++) {
3027                 parseElement(&mydata, elements[i]);
3028         }
3029
3030         if (!container_stack.empty()) {
3031                 errorstream << "Invalid formspec string: container was never closed!"
3032                         << std::endl;
3033         }
3034
3035         // If there are fields without explicit size[], add a "Proceed"
3036         // button and adjust size to fit all the fields.
3037         if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3038                 mydata.rect = core::rect<s32>(
3039                                 mydata.screensize.X / 2 - 580 / 2,
3040                                 mydata.screensize.Y / 2 - 300 / 2,
3041                                 mydata.screensize.X / 2 + 580 / 2,
3042                                 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3043                 );
3044
3045                 DesiredRect = mydata.rect;
3046                 recalculateAbsolutePosition(false);
3047                 mydata.basepos = getBasePos();
3048
3049                 {
3050                         v2s32 pos = mydata.basepos;
3051                         pos.Y = (mydata.simple_field_count + 2) * 60;
3052
3053                         v2s32 size = DesiredRect.getSize();
3054                         mydata.rect = core::rect<s32>(
3055                                         size.X / 2 - 70,       pos.Y,
3056                                         size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3057                         );
3058                         const wchar_t *text = wgettext("Proceed");
3059                         GUIButton::addButton(Environment, mydata.rect, this, 257, text);
3060                         delete[] text;
3061                 }
3062         }
3063
3064         //set initial focus if parser didn't set it
3065         focused_element = Environment->getFocus();
3066         if (!focused_element
3067                         || !isMyChild(focused_element)
3068                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3069                 setInitialFocus();
3070
3071         skin->setFont(old_font);
3072
3073         // legacy sorting
3074         if (m_formspec_version < 3)
3075                 legacySortElements(legacy_sort_start);
3076 }
3077
3078 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3079 {
3080         /*
3081                 Draw order for formspec_version <= 2:
3082                 -3  bgcolor
3083                 -2  background
3084                 -1  box
3085                 0   All other elements
3086                 1   image
3087                 2   item_image, item_image_button
3088                 3   list
3089                 4   label
3090         */
3091
3092         if (from == Children.end())
3093                 from = Children.begin();
3094         else
3095                 from++;
3096
3097         core::list<IGUIElement *>::Iterator to = Children.end();
3098         // 1: Copy into a sortable container
3099         std::vector<IGUIElement *> elements;
3100         for (auto it = from; it != to; ++it)
3101                 elements.emplace_back(*it);
3102
3103         // 2: Sort the container
3104         std::stable_sort(elements.begin(), elements.end(),
3105                         [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3106                 const FieldSpec *spec_a = getSpecByID(a->getID());
3107                 const FieldSpec *spec_b = getSpecByID(b->getID());
3108                 return spec_a && spec_b &&
3109                         spec_a->priority < spec_b->priority;
3110         });
3111
3112         // 3: Re-assign the pointers
3113         for (auto e : elements) {
3114                 *from = e;
3115                 from++;
3116         }
3117 }
3118
3119 #ifdef __ANDROID__
3120 bool GUIFormSpecMenu::getAndroidUIInput()
3121 {
3122         if (!hasAndroidUIInput())
3123                 return false;
3124
3125         std::string fieldname = m_jni_field_name;
3126         m_jni_field_name.clear();
3127
3128         for (std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3129                         iter != m_fields.end(); ++iter) {
3130
3131                 if (iter->fname != fieldname) {
3132                         continue;
3133                 }
3134                 IGUIElement *tochange = getElementFromId(iter->fid, true);
3135
3136                 if (tochange == 0) {
3137                         return false;
3138                 }
3139
3140                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
3141                         return false;
3142                 }
3143
3144                 std::string text = porting::getInputDialogValue();
3145
3146                 ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
3147         }
3148         return false;
3149 }
3150 #endif
3151
3152 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3153 {
3154         core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3155
3156         for (const GUIInventoryList *e : m_inventorylists) {
3157                 s32 item_index = e->getItemIndexAtPos(p);
3158                 if (item_index != -1)
3159                         return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3160                                         item_index);
3161         }
3162
3163         return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3164 }
3165
3166 void GUIFormSpecMenu::drawSelectedItem()
3167 {
3168         video::IVideoDriver* driver = Environment->getVideoDriver();
3169
3170         if (!m_selected_item) {
3171                 // reset rotation time
3172                 drawItemStack(driver, m_font, ItemStack(),
3173                                 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3174                                 m_client, IT_ROT_DRAGGED);
3175                 return;
3176         }
3177
3178         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3179         sanity_check(inv);
3180         InventoryList *list = inv->getList(m_selected_item->listname);
3181         sanity_check(list);
3182         ItemStack stack = list->getItem(m_selected_item->i);
3183         stack.count = m_selected_amount;
3184
3185         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3186         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3187         rect.constrainTo(driver->getViewPort());
3188         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3189 }
3190
3191 void GUIFormSpecMenu::drawMenu()
3192 {
3193         if (m_form_src) {
3194                 const std::string &newform = m_form_src->getForm();
3195                 if (newform != m_formspec_string) {
3196                         m_formspec_string = newform;
3197                         regenerateGui(m_screensize_old);
3198                 }
3199         }
3200
3201         gui::IGUISkin* skin = Environment->getSkin();
3202         sanity_check(skin != NULL);
3203         gui::IGUIFont *old_font = skin->getFont();
3204         skin->setFont(m_font);
3205
3206         m_hovered_item_tooltips.clear();
3207
3208         updateSelectedItem();
3209
3210         video::IVideoDriver* driver = Environment->getVideoDriver();
3211
3212         /*
3213                 Draw background color
3214         */
3215         v2u32 screenSize = driver->getScreenSize();
3216         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3217
3218         if (m_bgfullscreen)
3219                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3220         if (m_bgnonfullscreen)
3221                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3222
3223         /*
3224                 Draw rect_mode tooltip
3225         */
3226         m_tooltip_element->setVisible(false);
3227
3228         for (const auto &pair : m_tooltip_rects) {
3229                 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3230                 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3231                         const std::wstring &text = pair.second.tooltip;
3232                         if (!text.empty()) {
3233                                 showTooltip(text, pair.second.color, pair.second.bgcolor);
3234                                 break;
3235                         }
3236                 }
3237         }
3238
3239         /*
3240                 Draw backgrounds
3241         */
3242         for (gui::IGUIElement *e : m_backgrounds) {
3243                 e->setVisible(true);
3244                 e->draw();
3245                 e->setVisible(false);
3246         }
3247
3248         /*
3249                 Call base class
3250                 (This is where all the drawing happens.)
3251         */
3252         gui::IGUIElement::draw();
3253
3254         // Draw hovered item tooltips
3255         for (const std::string &tooltip : m_hovered_item_tooltips) {
3256                 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3257                                 m_default_tooltip_bgcolor);
3258         }
3259
3260         if (m_hovered_item_tooltips.empty()) {
3261                 // reset rotation time
3262                 drawItemStack(driver, m_font, ItemStack(),
3263                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3264                         NULL, m_client, IT_ROT_HOVERED);
3265         }
3266
3267 /* TODO find way to show tooltips on touchscreen */
3268 #ifndef HAVE_TOUCHSCREENGUI
3269         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3270 #endif
3271
3272         /*
3273                 Draw fields/buttons tooltips and update the mouse cursor
3274         */
3275         gui::IGUIElement *hovered =
3276                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3277
3278 #ifndef HAVE_TOUCHSCREENGUI
3279         gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3280                         getCursorControl();
3281         gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3282 #endif
3283         bool hovered_element_found = false;
3284
3285         if (hovered != NULL) {
3286                 s32 id = hovered->getID();
3287
3288                 u64 delta = 0;
3289                 if (id == -1) {
3290                         m_old_tooltip_id = id;
3291                 } else {
3292                         if (id == m_old_tooltip_id) {
3293                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3294                         } else {
3295                                 m_hovered_time = porting::getTimeMs();
3296                                 m_old_tooltip_id = id;
3297                         }
3298                 }
3299
3300                 // Find and update the current tooltip and cursor icon
3301                 if (id != -1) {
3302                         for (const FieldSpec &field : m_fields) {
3303
3304                                 if (field.fid != id)
3305                                         continue;
3306
3307                                 if (delta >= m_tooltip_show_delay) {
3308                                         const std::wstring &text = m_tooltips[field.fname].tooltip;
3309                                         if (!text.empty())
3310                                                 showTooltip(text, m_tooltips[field.fname].color,
3311                                                         m_tooltips[field.fname].bgcolor);
3312                                 }
3313
3314 #ifndef HAVE_TOUCHSCREENGUI
3315                                 if (current_cursor_icon != field.fcursor_icon)
3316                                         cursor_control->setActiveIcon(field.fcursor_icon);
3317 #endif
3318
3319                                 hovered_element_found = true;
3320
3321                                 break;
3322                         }
3323                 }
3324         }
3325
3326         if (!hovered_element_found) {
3327                 // no element is hovered
3328 #ifndef HAVE_TOUCHSCREENGUI
3329                 if (current_cursor_icon != ECI_NORMAL)
3330                         cursor_control->setActiveIcon(ECI_NORMAL);
3331 #endif
3332         }
3333
3334         m_tooltip_element->draw();
3335
3336         /*
3337                 Draw dragged item stack
3338         */
3339         drawSelectedItem();
3340
3341         skin->setFont(old_font);
3342 }
3343
3344
3345 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3346         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3347 {
3348         EnrichedString ntext(text);
3349         ntext.setDefaultColor(color);
3350         ntext.setBackground(bgcolor);
3351
3352         setStaticText(m_tooltip_element, ntext);
3353
3354         // Tooltip size and offset
3355         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3356         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3357
3358         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3359         int tooltip_offset_x = m_btn_height;
3360         int tooltip_offset_y = m_btn_height;
3361 #ifdef __ANDROID__
3362         tooltip_offset_x *= 3;
3363         tooltip_offset_y  = 0;
3364         if (m_pointer.X > (s32)screenSize.X / 2)
3365                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3366 #endif
3367
3368         // Calculate and set the tooltip position
3369         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3370         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3371         if (tooltip_x + tooltip_width > (s32)screenSize.X)
3372                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
3373         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3374                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3375
3376         m_tooltip_element->setRelativePosition(
3377                 core::rect<s32>(
3378                         core::position2d<s32>(tooltip_x, tooltip_y),
3379                         core::dimension2d<s32>(tooltip_width, tooltip_height)
3380                 )
3381         );
3382
3383         // Display the tooltip
3384         m_tooltip_element->setVisible(true);
3385         bringToFront(m_tooltip_element);
3386 }
3387
3388 void GUIFormSpecMenu::updateSelectedItem()
3389 {
3390         verifySelectedItem();
3391
3392         // If craftresult is nonempty and nothing else is selected, select it now.
3393         if (!m_selected_item) {
3394                 for (const GUIInventoryList *e : m_inventorylists) {
3395                         if (e->getListname() != "craftpreview")
3396                                 continue;
3397
3398                         Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3399                         if (!inv)
3400                                 continue;
3401
3402                         InventoryList *list = inv->getList("craftresult");
3403
3404                         if (!list || list->getSize() == 0)
3405                                 continue;
3406
3407                         const ItemStack &item = list->getItem(0);
3408                         if (item.empty())
3409                                 continue;
3410
3411                         // Grab selected item from the crafting result list
3412                         m_selected_item = new GUIInventoryList::ItemSpec;
3413                         m_selected_item->inventoryloc = e->getInventoryloc();
3414                         m_selected_item->listname = "craftresult";
3415                         m_selected_item->i = 0;
3416                         m_selected_amount = item.count;
3417                         m_selected_dragging = false;
3418                         break;
3419                 }
3420         }
3421
3422         // If craftresult is selected, keep the whole stack selected
3423         if (m_selected_item && m_selected_item->listname == "craftresult")
3424                 m_selected_amount = verifySelectedItem().count;
3425 }
3426
3427 ItemStack GUIFormSpecMenu::verifySelectedItem()
3428 {
3429         // If the selected stack has become empty for some reason, deselect it.
3430         // If the selected stack has become inaccessible, deselect it.
3431         // If the selected stack has become smaller, adjust m_selected_amount.
3432         // Return the selected stack.
3433
3434         if (m_selected_item) {
3435                 if (m_selected_item->isValid()) {
3436                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3437                         if (inv) {
3438                                 InventoryList *list = inv->getList(m_selected_item->listname);
3439                                 if (list && (u32) m_selected_item->i < list->getSize()) {
3440                                         ItemStack stack = list->getItem(m_selected_item->i);
3441                                         if (!m_selected_swap.empty()) {
3442                                                 if (m_selected_swap.name == stack.name &&
3443                                                                 m_selected_swap.count == stack.count)
3444                                                         m_selected_swap.clear();
3445                                         } else {
3446                                                 m_selected_amount = std::min(m_selected_amount, stack.count);
3447                                         }
3448
3449                                         if (!stack.empty())
3450                                                 return stack;
3451                                 }
3452                         }
3453                 }
3454
3455                 // selection was not valid
3456                 delete m_selected_item;
3457                 m_selected_item = nullptr;
3458                 m_selected_amount = 0;
3459                 m_selected_dragging = false;
3460         }
3461         return ItemStack();
3462 }
3463
3464 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3465 {
3466         if(m_text_dst)
3467         {
3468                 StringMap fields;
3469
3470                 if (quitmode == quit_mode_accept) {
3471                         fields["quit"] = "true";
3472                 }
3473
3474                 if (quitmode == quit_mode_cancel) {
3475                         fields["quit"] = "true";
3476                         m_text_dst->gotText(fields);
3477                         return;
3478                 }
3479
3480                 if (current_keys_pending.key_down) {
3481                         fields["key_down"] = "true";
3482                         current_keys_pending.key_down = false;
3483                 }
3484
3485                 if (current_keys_pending.key_up) {
3486                         fields["key_up"] = "true";
3487                         current_keys_pending.key_up = false;
3488                 }
3489
3490                 if (current_keys_pending.key_enter) {
3491                         fields["key_enter"] = "true";
3492                         current_keys_pending.key_enter = false;
3493                 }
3494
3495                 if (!current_field_enter_pending.empty()) {
3496                         fields["key_enter_field"] = current_field_enter_pending;
3497                         current_field_enter_pending = "";
3498                 }
3499
3500                 if (current_keys_pending.key_escape) {
3501                         fields["key_escape"] = "true";
3502                         current_keys_pending.key_escape = false;
3503                 }
3504
3505                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3506                         if(s.send) {
3507                                 std::string name = s.fname;
3508                                 if (s.ftype == f_Button) {
3509                                         fields[name] = wide_to_utf8(s.flabel);
3510                                 } else if (s.ftype == f_Table) {
3511                                         GUITable *table = getTable(s.fname);
3512                                         if (table) {
3513                                                 fields[name] = table->checkEvent();
3514                                         }
3515                                 }
3516                                 else if(s.ftype == f_DropDown) {
3517                                         // no dynamic cast possible due to some distributions shipped
3518                                         // without rtti support in irrlicht
3519                                         IGUIElement *element = getElementFromId(s.fid, true);
3520                                         gui::IGUIComboBox *e = NULL;
3521                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3522                                                 e = static_cast<gui::IGUIComboBox*>(element);
3523                                         } else {
3524                                                 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3525                                                                 << "field without dropdown element" << std::endl;
3526                                                 continue;
3527                                         }
3528                                         s32 selected = e->getSelected();
3529                                         if (selected >= 0) {
3530                                                 std::vector<std::string> *dropdown_values =
3531                                                         getDropDownValues(s.fname);
3532                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3533                                                         fields[name] = (*dropdown_values)[selected];
3534                                                 }
3535                                         }
3536                                 }
3537                                 else if (s.ftype == f_TabHeader) {
3538                                         // no dynamic cast possible due to some distributions shipped
3539                                         // without rttzi support in irrlicht
3540                                         IGUIElement *element = getElementFromId(s.fid, true);
3541                                         gui::IGUITabControl *e = nullptr;
3542                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3543                                                 e = static_cast<gui::IGUITabControl *>(element);
3544                                         }
3545
3546                                         if (e != 0) {
3547                                                 std::stringstream ss;
3548                                                 ss << (e->getActiveTab() +1);
3549                                                 fields[name] = ss.str();
3550                                         }
3551                                 }
3552                                 else if (s.ftype == f_CheckBox) {
3553                                         // no dynamic cast possible due to some distributions shipped
3554                                         // without rtti support in irrlicht
3555                                         IGUIElement *element = getElementFromId(s.fid, true);
3556                                         gui::IGUICheckBox *e = nullptr;
3557                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3558                                                 e = static_cast<gui::IGUICheckBox*>(element);
3559                                         }
3560
3561                                         if (e != 0) {
3562                                                 if (e->isChecked())
3563                                                         fields[name] = "true";
3564                                                 else
3565                                                         fields[name] = "false";
3566                                         }
3567                                 }
3568                                 else if (s.ftype == f_ScrollBar) {
3569                                         // no dynamic cast possible due to some distributions shipped
3570                                         // without rtti support in irrlicht
3571                                         IGUIElement *element = getElementFromId(s.fid, true);
3572                                         GUIScrollBar *e = nullptr;
3573                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3574                                                 e = static_cast<GUIScrollBar *>(element);
3575
3576                                         if (e) {
3577                                                 std::stringstream os;
3578                                                 os << e->getPos();
3579                                                 if (s.fdefault == L"Changed")
3580                                                         fields[name] = "CHG:" + os.str();
3581                                                 else
3582                                                         fields[name] = "VAL:" + os.str();
3583                                         }
3584                                 }
3585                                 else {
3586                                         IGUIElement *e = getElementFromId(s.fid, true);
3587                                         if (e)
3588                                                 fields[name] = wide_to_utf8(e->getText());
3589                                 }
3590                         }
3591                 }
3592
3593                 m_text_dst->gotText(fields);
3594         }
3595 }
3596
3597 static bool isChild(gui::IGUIElement *tocheck, gui::IGUIElement *parent)
3598 {
3599         while (tocheck) {
3600                 if (tocheck == parent) {
3601                         return true;
3602                 }
3603                 tocheck = tocheck->getParent();
3604         }
3605         return false;
3606 }
3607
3608 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3609 {
3610         // The IGUITabControl renders visually using the skin's selected
3611         // font, which we override for the duration of form drawing,
3612         // but computes tab hotspots based on how it would have rendered
3613         // using the font that is selected at the time of button release.
3614         // To make these two consistent, temporarily override the skin's
3615         // font while the IGUITabControl is processing the event.
3616         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3617                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3618                 s32 x = event.MouseInput.X;
3619                 s32 y = event.MouseInput.Y;
3620                 gui::IGUIElement *hovered =
3621                         Environment->getRootGUIElement()->getElementFromPoint(
3622                                 core::position2d<s32>(x, y));
3623                 if (hovered && isMyChild(hovered) &&
3624                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3625                         gui::IGUISkin* skin = Environment->getSkin();
3626                         sanity_check(skin != NULL);
3627                         gui::IGUIFont *old_font = skin->getFont();
3628                         skin->setFont(m_font);
3629                         bool retval = hovered->OnEvent(event);
3630                         skin->setFont(old_font);
3631                         return retval;
3632                 }
3633         }
3634
3635         // Fix Esc/Return key being eaten by checkboxen and tables
3636         if (event.EventType == EET_KEY_INPUT_EVENT) {
3637                         KeyPress kp(event.KeyInput);
3638                 if (kp == EscapeKey || kp == CancelKey
3639                                 || kp == getKeySetting("keymap_inventory")
3640                                 || event.KeyInput.Key==KEY_RETURN) {
3641                         gui::IGUIElement *focused = Environment->getFocus();
3642                         if (focused && isMyChild(focused) &&
3643                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
3644                                         focused->getType() == gui::EGUIET_CHECK_BOX) &&
3645                                         (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3646                                         event.KeyInput.Key != KEY_RETURN)) {
3647                                 OnEvent(event);
3648                                 return true;
3649                         }
3650                 }
3651         }
3652         // Mouse wheel and move events: send to hovered element instead of focused
3653         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3654                         (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3655                          event.MouseInput.Event == EMIE_MOUSE_MOVED)) {
3656                 s32 x = event.MouseInput.X;
3657                 s32 y = event.MouseInput.Y;
3658                 gui::IGUIElement *hovered =
3659                         Environment->getRootGUIElement()->getElementFromPoint(
3660                                 core::position2d<s32>(x, y));
3661                 if (hovered && isMyChild(hovered)) {
3662                         hovered->OnEvent(event);
3663                         return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3664                 }
3665         }
3666
3667         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3668                 s32 x = event.MouseInput.X;
3669                 s32 y = event.MouseInput.Y;
3670                 gui::IGUIElement *hovered =
3671                         Environment->getRootGUIElement()->getElementFromPoint(
3672                                 core::position2d<s32>(x, y));
3673                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3674                         m_old_tooltip_id = -1;
3675                 }
3676                 if (!isChild(hovered, this)) {
3677                         if (DoubleClickDetection(event)) {
3678                                 return true;
3679                         }
3680                 }
3681         }
3682
3683         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3684                 /* TODO add a check like:
3685                 if (event.JoystickEvent != joystick_we_listen_for)
3686                         return false;
3687                 */
3688                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3689                 if (handled) {
3690                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
3691                                 tryClose();
3692                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3693                                 if (m_allowclose) {
3694                                         acceptInput(quit_mode_accept);
3695                                         quitMenu();
3696                                 }
3697                         }
3698                 }
3699                 return handled;
3700         }
3701
3702         return GUIModalMenu::preprocessEvent(event);
3703 }
3704
3705 /******************************************************************************/
3706 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3707 {
3708         /* The following code is for capturing double-clicks of the mouse button
3709          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3710          * -- which closes the form -- under some circumstances.
3711          *
3712          * There have been many github issues reporting this as a bug even though it
3713          * was an intended feature.  For this reason, remapping the double-click as
3714          * an ESC must be explicitly set when creating this class via the
3715          * /p remap_dbl_click parameter of the constructor.
3716          */
3717
3718         if (!m_remap_dbl_click)
3719                 return false;
3720
3721         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3722                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3723                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3724
3725                 m_doubleclickdetect[1].pos  = m_pointer;
3726                 m_doubleclickdetect[1].time = porting::getTimeMs();
3727         }
3728         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3729                 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3730                 if (delta > 400) {
3731                         return false;
3732                 }
3733
3734                 double squaredistance =
3735                                 m_doubleclickdetect[0].pos
3736                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3737
3738                 if (squaredistance > (30*30)) {
3739                         return false;
3740                 }
3741
3742                 SEvent* translated = new SEvent();
3743                 assert(translated != 0);
3744                 //translate doubleclick to escape
3745                 memset(translated, 0, sizeof(SEvent));
3746                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3747                 translated->KeyInput.Key         = KEY_ESCAPE;
3748                 translated->KeyInput.Control     = false;
3749                 translated->KeyInput.Shift       = false;
3750                 translated->KeyInput.PressedDown = true;
3751                 translated->KeyInput.Char        = 0;
3752                 OnEvent(*translated);
3753
3754                 // no need to send the key up event as we're already deleted
3755                 // and no one else did notice this event
3756                 delete translated;
3757                 return true;
3758         }
3759
3760         return false;
3761 }
3762
3763 void GUIFormSpecMenu::tryClose()
3764 {
3765         if (m_allowclose) {
3766                 doPause = false;
3767                 acceptInput(quit_mode_cancel);
3768                 quitMenu();
3769         } else {
3770                 m_text_dst->gotText(L"MenuQuit");
3771         }
3772 }
3773
3774 enum ButtonEventType : u8
3775 {
3776         BET_LEFT,
3777         BET_RIGHT,
3778         BET_MIDDLE,
3779         BET_WHEEL_UP,
3780         BET_WHEEL_DOWN,
3781         BET_UP,
3782         BET_DOWN,
3783         BET_MOVE,
3784         BET_OTHER
3785 };
3786
3787 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3788 {
3789         if (event.EventType==EET_KEY_INPUT_EVENT) {
3790                 KeyPress kp(event.KeyInput);
3791                 if (event.KeyInput.PressedDown && (
3792                                 (kp == EscapeKey) || (kp == CancelKey) ||
3793                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3794                         tryClose();
3795                         return true;
3796                 }
3797
3798                 if (m_client != NULL && event.KeyInput.PressedDown &&
3799                                 (kp == getKeySetting("keymap_screenshot"))) {
3800                         m_client->makeScreenshot();
3801                 }
3802                 if (event.KeyInput.PressedDown &&
3803                         (event.KeyInput.Key==KEY_RETURN ||
3804                          event.KeyInput.Key==KEY_UP ||
3805                          event.KeyInput.Key==KEY_DOWN)
3806                         ) {
3807                         switch (event.KeyInput.Key) {
3808                                 case KEY_RETURN:
3809                                         current_keys_pending.key_enter = true;
3810                                         break;
3811                                 case KEY_UP:
3812                                         current_keys_pending.key_up = true;
3813                                         break;
3814                                 case KEY_DOWN:
3815                                         current_keys_pending.key_down = true;
3816                                         break;
3817                                 break;
3818                                 default:
3819                                         //can't happen at all!
3820                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3821                                         break;
3822                         }
3823                         if (current_keys_pending.key_enter && m_allowclose) {
3824                                 acceptInput(quit_mode_accept);
3825                                 quitMenu();
3826                         } else {
3827                                 acceptInput();
3828                         }
3829                         return true;
3830                 }
3831
3832         }
3833
3834         /* Mouse event other than movement, or crossing the border of inventory
3835           field while holding right mouse button
3836          */
3837         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3838                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3839                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3840                           event.MouseInput.isRightPressed() &&
3841                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3842
3843                 // Get selected item and hovered/clicked item (s)
3844
3845                 m_old_tooltip_id = -1;
3846                 updateSelectedItem();
3847                 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
3848
3849                 Inventory *inv_selected = NULL;
3850                 Inventory *inv_s = NULL;
3851                 InventoryList *list_s = NULL;
3852
3853                 if (m_selected_item) {
3854                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3855                         sanity_check(inv_selected);
3856                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3857                 }
3858
3859                 u32 s_count = 0;
3860
3861                 if (s.isValid())
3862                 do { // breakable
3863                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3864
3865                         if (!inv_s) {
3866                                 errorstream << "InventoryMenu: The selected inventory location "
3867                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3868                                                 << std::endl;
3869                                 s.i = -1;  // make it invalid again
3870                                 break;
3871                         }
3872
3873                         list_s = inv_s->getList(s.listname);
3874                         if (list_s == NULL) {
3875                                 verbosestream << "InventoryMenu: The selected inventory list \""
3876                                                 << s.listname << "\" does not exist" << std::endl;
3877                                 s.i = -1;  // make it invalid again
3878                                 break;
3879                         }
3880
3881                         if ((u32)s.i >= list_s->getSize()) {
3882                                 infostream << "InventoryMenu: The selected inventory list \""
3883                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
3884                                                 << list_s->getSize() << ")" << std::endl;
3885                                 s.i = -1;  // make it invalid again
3886                                 break;
3887                         }
3888
3889                         s_count = list_s->getItem(s.i).count;
3890                 } while(0);
3891
3892                 bool identical = m_selected_item && s.isValid() &&
3893                         (inv_selected == inv_s) &&
3894                         (m_selected_item->listname == s.listname) &&
3895                         (m_selected_item->i == s.i);
3896
3897                 ButtonEventType button = BET_LEFT;
3898                 ButtonEventType updown = BET_OTHER;
3899                 switch (event.MouseInput.Event) {
3900                 case EMIE_LMOUSE_PRESSED_DOWN:
3901                         button = BET_LEFT; updown = BET_DOWN;
3902                         break;
3903                 case EMIE_RMOUSE_PRESSED_DOWN:
3904                         button = BET_RIGHT; updown = BET_DOWN;
3905                         break;
3906                 case EMIE_MMOUSE_PRESSED_DOWN:
3907                         button = BET_MIDDLE; updown = BET_DOWN;
3908                         break;
3909                 case EMIE_MOUSE_WHEEL:
3910                         button = (event.MouseInput.Wheel > 0) ?
3911                                 BET_WHEEL_UP : BET_WHEEL_DOWN;
3912                         updown = BET_DOWN;
3913                         break;
3914                 case EMIE_LMOUSE_LEFT_UP:
3915                         button = BET_LEFT; updown = BET_UP;
3916                         break;
3917                 case EMIE_RMOUSE_LEFT_UP:
3918                         button = BET_RIGHT; updown = BET_UP;
3919                         break;
3920                 case EMIE_MMOUSE_LEFT_UP:
3921                         button = BET_MIDDLE; updown = BET_UP;
3922                         break;
3923                 case EMIE_MOUSE_MOVED:
3924                         updown = BET_MOVE;
3925                         break;
3926                 default:
3927                         break;
3928                 }
3929
3930                 // Set this number to a positive value to generate a move action
3931                 // from m_selected_item to s.
3932                 u32 move_amount = 0;
3933
3934                 // Set this number to a positive value to generate a move action
3935                 // from s to the next inventory ring.
3936                 u32 shift_move_amount = 0;
3937
3938                 // Set this number to a positive value to generate a drop action
3939                 // from m_selected_item.
3940                 u32 drop_amount = 0;
3941
3942                 // Set this number to a positive value to generate a craft action at s.
3943                 u32 craft_amount = 0;
3944
3945                 switch (updown) {
3946                 case BET_DOWN:
3947                         // Some mouse button has been pressed
3948
3949                         //infostream << "Mouse button " << button << " pressed at p=("
3950                         //      << event.MouseInput.X << "," << event.MouseInput.Y << ")"
3951                         //      << std::endl;
3952
3953                         m_selected_dragging = false;
3954
3955                         if (s.isValid() && s.listname == "craftpreview") {
3956                                 // Craft preview has been clicked: craft
3957                                 craft_amount = (button == BET_MIDDLE ? 10 : 1);
3958                         } else if (!m_selected_item) {
3959                                 if (s_count && button != BET_WHEEL_UP) {
3960                                         // Non-empty stack has been clicked: select or shift-move it
3961                                         m_selected_item = new GUIInventoryList::ItemSpec(s);
3962
3963                                         u32 count;
3964                                         if (button == BET_RIGHT)
3965                                                 count = (s_count + 1) / 2;
3966                                         else if (button == BET_MIDDLE)
3967                                                 count = MYMIN(s_count, 10);
3968                                         else if (button == BET_WHEEL_DOWN)
3969                                                 count = 1;
3970                                         else  // left
3971                                                 count = s_count;
3972
3973                                         if (!event.MouseInput.Shift) {
3974                                                 // no shift: select item
3975                                                 m_selected_amount = count;
3976                                                 m_selected_dragging = button != BET_WHEEL_DOWN;
3977                                                 m_auto_place = false;
3978                                         } else {
3979                                                 // shift pressed: move item, right click moves 1
3980                                                 shift_move_amount = button == BET_RIGHT ? 1 : count;
3981                                         }
3982                                 }
3983                         } else { // m_selected_item != NULL
3984                                 assert(m_selected_amount >= 1);
3985
3986                                 if (s.isValid()) {
3987                                         // Clicked a slot: move
3988                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
3989                                                 move_amount = 1;
3990                                         else if (button == BET_MIDDLE)
3991                                                 move_amount = MYMIN(m_selected_amount, 10);
3992                                         else if (button == BET_LEFT)
3993                                                 move_amount = m_selected_amount;
3994                                         // else wheeldown
3995
3996                                         if (identical) {
3997                                                 if (button == BET_WHEEL_DOWN) {
3998                                                         if (m_selected_amount < s_count)
3999                                                                 ++m_selected_amount;
4000                                                 } else {
4001                                                         if (move_amount >= m_selected_amount)
4002                                                                 m_selected_amount = 0;
4003                                                         else
4004                                                                 m_selected_amount -= move_amount;
4005                                                         move_amount = 0;
4006                                                 }
4007                                         }
4008                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4009                                                 && button != BET_WHEEL_DOWN) {
4010                                         // Clicked outside of the window: drop
4011                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4012                                                 drop_amount = 1;
4013                                         else if (button == BET_MIDDLE)
4014                                                 drop_amount = MYMIN(m_selected_amount, 10);
4015                                         else  // left
4016                                                 drop_amount = m_selected_amount;
4017                                 }
4018                         }
4019                 break;
4020                 case BET_UP:
4021                         // Some mouse button has been released
4022
4023                         //infostream<<"Mouse button "<<button<<" released at p=("
4024                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
4025
4026                         if (m_selected_dragging && m_selected_item) {
4027                                 if (s.isValid()) {
4028                                         if (!identical) {
4029                                                 // Dragged to different slot: move all selected
4030                                                 move_amount = m_selected_amount;
4031                                         }
4032                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4033                                         // Dragged outside of window: drop all selected
4034                                         drop_amount = m_selected_amount;
4035                                 }
4036                         }
4037
4038                         m_selected_dragging = false;
4039                         // Keep track of whether the mouse button be released
4040                         // One click is drag without dropping. Click + release
4041                         // + click changes to drop item when moved mode
4042                         if (m_selected_item)
4043                                 m_auto_place = true;
4044                 break;
4045                 case BET_MOVE:
4046                         // Mouse has been moved and rmb is down and mouse pointer just
4047                         // entered a new inventory field (checked in the entry-if, this
4048                         // is the only action here that is generated by mouse movement)
4049                         if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4050                                 // Move 1 item
4051                                 // TODO: middle mouse to move 10 items might be handy
4052                                 if (m_auto_place) {
4053                                         // Only move an item if the destination slot is empty
4054                                         // or contains the same item type as what is going to be
4055                                         // moved
4056                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4057                                         InventoryList *list_to = list_s;
4058                                         assert(list_from && list_to);
4059                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4060                                         ItemStack stack_to = list_to->getItem(s.i);
4061                                         if (stack_to.empty() || stack_to.name == stack_from.name)
4062                                                 move_amount = 1;
4063                                 }
4064                         }
4065                 break;
4066                 default:
4067                         break;
4068                 }
4069
4070                 // Possibly send inventory action to server
4071                 if (move_amount > 0) {
4072                         // Send IAction::Move
4073
4074                         assert(m_selected_item && m_selected_item->isValid());
4075                         assert(s.isValid());
4076
4077                         assert(inv_selected && inv_s);
4078                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4079                         InventoryList *list_to = list_s;
4080                         assert(list_from && list_to);
4081                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4082                         ItemStack stack_to = list_to->getItem(s.i);
4083
4084                         // Check how many items can be moved
4085                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4086                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4087                         bool move = true;
4088                         // If source stack cannot be added to destination stack at all,
4089                         // they are swapped
4090                         if (leftover.count == stack_from.count &&
4091                                         leftover.name == stack_from.name) {
4092
4093                                 if (m_selected_swap.empty()) {
4094                                         m_selected_amount = stack_to.count;
4095                                         m_selected_dragging = false;
4096
4097                                         // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4098                                         // Skip next validation checks due async inventory calls
4099                                         m_selected_swap = stack_to;
4100                                 } else {
4101                                         move = false;
4102                                 }
4103                         }
4104                         // Source stack goes fully into destination stack
4105                         else if (leftover.empty()) {
4106                                 m_selected_amount -= move_amount;
4107                         }
4108                         // Source stack goes partly into destination stack
4109                         else {
4110                                 move_amount -= leftover.count;
4111                                 m_selected_amount -= move_amount;
4112                         }
4113
4114                         if (move) {
4115                                 infostream << "Handing IAction::Move to manager" << std::endl;
4116                                 IMoveAction *a = new IMoveAction();
4117                                 a->count = move_amount;
4118                                 a->from_inv = m_selected_item->inventoryloc;
4119                                 a->from_list = m_selected_item->listname;
4120                                 a->from_i = m_selected_item->i;
4121                                 a->to_inv = s.inventoryloc;
4122                                 a->to_list = s.listname;
4123                                 a->to_i = s.i;
4124                                 m_invmgr->inventoryAction(a);
4125                         }
4126                 } else if (shift_move_amount > 0) {
4127                         u32 mis = m_inventory_rings.size();
4128                         u32 i = 0;
4129                         for (; i < mis; i++) {
4130                                 const ListRingSpec &sp = m_inventory_rings[i];
4131                                 if (sp.inventoryloc == s.inventoryloc
4132                                                 && sp.listname == s.listname)
4133                                         break;
4134                         }
4135                         do {
4136                                 if (i >= mis) // if not found
4137                                         break;
4138                                 u32 to_inv_ind = (i + 1) % mis;
4139                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4140                                 InventoryList *list_from = list_s;
4141                                 if (!s.isValid())
4142                                         break;
4143                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4144                                 if (!inv_to)
4145                                         break;
4146                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4147                                 if (!list_to)
4148                                         break;
4149                                 ItemStack stack_from = list_from->getItem(s.i);
4150                                 assert(shift_move_amount <= stack_from.count);
4151
4152                                 infostream << "Handing IAction::Move to manager" << std::endl;
4153                                 IMoveAction *a = new IMoveAction();
4154                                 a->count = shift_move_amount;
4155                                 a->from_inv = s.inventoryloc;
4156                                 a->from_list = s.listname;
4157                                 a->from_i = s.i;
4158                                 a->to_inv = to_inv_sp.inventoryloc;
4159                                 a->to_list = to_inv_sp.listname;
4160                                 a->move_somewhere = true;
4161                                 m_invmgr->inventoryAction(a);
4162                         } while (0);
4163                 } else if (drop_amount > 0) {
4164                         // Send IAction::Drop
4165
4166                         assert(m_selected_item && m_selected_item->isValid());
4167                         assert(inv_selected);
4168                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4169                         assert(list_from);
4170                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4171
4172                         // Check how many items can be dropped
4173                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4174                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4175                         m_selected_amount -= drop_amount;
4176
4177                         infostream << "Handing IAction::Drop to manager" << std::endl;
4178                         IDropAction *a = new IDropAction();
4179                         a->count = drop_amount;
4180                         a->from_inv = m_selected_item->inventoryloc;
4181                         a->from_list = m_selected_item->listname;
4182                         a->from_i = m_selected_item->i;
4183                         m_invmgr->inventoryAction(a);
4184                 } else if (craft_amount > 0) {
4185                         assert(s.isValid());
4186
4187                         // if there are no items selected or the selected item
4188                         // belongs to craftresult list, proceed with crafting
4189                         if (!m_selected_item ||
4190                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4191
4192                                 assert(inv_s);
4193
4194                                 // Send IACTION_CRAFT
4195                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4196                                 ICraftAction *a = new ICraftAction();
4197                                 a->count = craft_amount;
4198                                 a->craft_inv = s.inventoryloc;
4199                                 m_invmgr->inventoryAction(a);
4200                         }
4201                 }
4202
4203                 // If m_selected_amount has been decreased to zero, deselect
4204                 if (m_selected_amount == 0) {
4205                         m_selected_swap.clear();
4206                         delete m_selected_item;
4207                         m_selected_item = nullptr;
4208                         m_selected_amount = 0;
4209                         m_selected_dragging = false;
4210                 }
4211                 m_old_pointer = m_pointer;
4212         }
4213
4214         if (event.EventType == EET_GUI_EVENT) {
4215                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4216                                 && isVisible()) {
4217                         // find the element that was clicked
4218                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4219                                 if ((s.ftype == f_TabHeader) &&
4220                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4221                                         s.send = true;
4222                                         acceptInput();
4223                                         s.send = false;
4224                                         return true;
4225                                 }
4226                         }
4227                 }
4228                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4229                                 && isVisible()) {
4230                         if (!canTakeFocus(event.GUIEvent.Element)) {
4231                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4232                                                 <<std::endl;
4233                                 // Returning true disables focus change
4234                                 return true;
4235                         }
4236                 }
4237                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4238                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4239                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4240                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4241                         unsigned int btn_id = event.GUIEvent.Caller->getID();
4242
4243                         if (btn_id == 257) {
4244                                 if (m_allowclose) {
4245                                         acceptInput(quit_mode_accept);
4246                                         quitMenu();
4247                                 } else {
4248                                         acceptInput();
4249                                         m_text_dst->gotText(L"ExitButton");
4250                                 }
4251                                 // quitMenu deallocates menu
4252                                 return true;
4253                         }
4254
4255                         // find the element that was clicked
4256                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4257                                 // if its a button, set the send field so
4258                                 // lua knows which button was pressed
4259                                 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
4260                                                 s.fid == event.GUIEvent.Caller->getID()) {
4261                                         s.send = true;
4262                                         if (s.is_exit) {
4263                                                 if (m_allowclose) {
4264                                                         acceptInput(quit_mode_accept);
4265                                                         quitMenu();
4266                                                 } else {
4267                                                         m_text_dst->gotText(L"ExitButton");
4268                                                 }
4269                                                 return true;
4270                                         }
4271
4272                                         acceptInput(quit_mode_no);
4273                                         s.send = false;
4274                                         return true;
4275
4276                                 } else if ((s.ftype == f_DropDown) &&
4277                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4278                                         // only send the changed dropdown
4279                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4280                                                 if (s2.ftype == f_DropDown) {
4281                                                         s2.send = false;
4282                                                 }
4283                                         }
4284                                         s.send = true;
4285                                         acceptInput(quit_mode_no);
4286
4287                                         // revert configuration to make sure dropdowns are sent on
4288                                         // regular button click
4289                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4290                                                 if (s2.ftype == f_DropDown) {
4291                                                         s2.send = true;
4292                                                 }
4293                                         }
4294                                         return true;
4295                                 } else if ((s.ftype == f_ScrollBar) &&
4296                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4297                                         s.fdefault = L"Changed";
4298                                         acceptInput(quit_mode_no);
4299                                         s.fdefault = L"";
4300                                 } else if ((s.ftype == f_Unknown) &&
4301                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4302                                         s.send = true;
4303                                         acceptInput();
4304                                         s.send = false;
4305                                 }
4306                         }
4307                 }
4308
4309                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4310                         if (event.GUIEvent.Caller->getID() > 257) {
4311                                 bool close_on_enter = true;
4312                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4313                                         if (s.ftype == f_Unknown &&
4314                                                         s.fid == event.GUIEvent.Caller->getID()) {
4315                                                 current_field_enter_pending = s.fname;
4316                                                 std::unordered_map<std::string, bool>::const_iterator it =
4317                                                         field_close_on_enter.find(s.fname);
4318                                                 if (it != field_close_on_enter.end())
4319                                                         close_on_enter = (*it).second;
4320
4321                                                 break;
4322                                         }
4323                                 }
4324
4325                                 if (m_allowclose && close_on_enter) {
4326                                         current_keys_pending.key_enter = true;
4327                                         acceptInput(quit_mode_accept);
4328                                         quitMenu();
4329                                 } else {
4330                                         current_keys_pending.key_enter = true;
4331                                         acceptInput();
4332                                 }
4333                                 // quitMenu deallocates menu
4334                                 return true;
4335                         }
4336                 }
4337
4338                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4339                         int current_id = event.GUIEvent.Caller->getID();
4340                         if (current_id > 257) {
4341                                 // find the element that was clicked
4342                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4343                                         // if it's a table, set the send field
4344                                         // so lua knows which table was changed
4345                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
4346                                                 s.send = true;
4347                                                 acceptInput();
4348                                                 s.send=false;
4349                                         }
4350                                 }
4351                                 return true;
4352                         }
4353                 }
4354         }
4355
4356         return Parent ? Parent->OnEvent(event) : false;
4357 }
4358
4359 /**
4360  * get name of element by element id
4361  * @param id of element
4362  * @return name string or empty string
4363  */
4364 std::string GUIFormSpecMenu::getNameByID(s32 id)
4365 {
4366         for (FieldSpec &spec : m_fields) {
4367                 if (spec.fid == id)
4368                         return spec.fname;
4369         }
4370         return "";
4371 }
4372
4373
4374 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4375 {
4376         for (FieldSpec &spec : m_fields) {
4377                 if (spec.fid == id)
4378                         return &spec;
4379         }
4380         return nullptr;
4381 }
4382
4383 /**
4384  * get label of element by id
4385  * @param id of element
4386  * @return label string or empty string
4387  */
4388 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4389 {
4390         for (FieldSpec &spec : m_fields) {
4391                 if (spec.fid == id)
4392                         return spec.flabel;
4393         }
4394         return L"";
4395 }
4396
4397 StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
4398                 const std::string &name, const std::string &parent_type) {
4399         StyleSpec ret;
4400
4401         if (!parent_type.empty()) {
4402                 auto it = theme_by_type.find(parent_type);
4403                 if (it != theme_by_type.end()) {
4404                         ret |= it->second;
4405                 }
4406         }
4407
4408         auto it = theme_by_type.find(type);
4409         if (it != theme_by_type.end()) {
4410                 ret |= it->second;
4411         }
4412
4413         it = theme_by_name.find(name);
4414         if (it != theme_by_name.end()) {
4415                 ret |= it->second;
4416         }
4417
4418         return ret;
4419 }