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