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