]> git.lizzy.rs Git - minetest.git/blob - src/gui/guiFormSpecMenu.cpp
Fix error message caused by adding new parameter to background (#8922)
[minetest.git] / src / gui / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <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                         e->drop();
1215                 } else if (is_editable) {
1216                         e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1217                                 this, spec.fid);
1218                 }
1219         }
1220
1221         if (e) {
1222                 if (is_editable && spec.fname == data->focused_fieldname)
1223                         Environment->setFocus(e);
1224
1225                 if (is_multiline) {
1226                         e->setMultiLine(true);
1227                         e->setWordWrap(true);
1228                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1229                 } else {
1230                         irr::SEvent evt;
1231                         evt.EventType            = EET_KEY_INPUT_EVENT;
1232                         evt.KeyInput.Key         = KEY_END;
1233                         evt.KeyInput.Char        = 0;
1234                         evt.KeyInput.Control     = 0;
1235                         evt.KeyInput.Shift       = 0;
1236                         evt.KeyInput.PressedDown = true;
1237                         e->OnEvent(evt);
1238                 }
1239
1240                 auto style = getStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1241                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1242                 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1243                 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1244                 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1245                         e->setDrawBackground(false);
1246                 }
1247         }
1248
1249         if (!spec.flabel.empty()) {
1250                 int font_height = g_fontengine->getTextHeight();
1251                 rect.UpperLeftCorner.Y -= font_height;
1252                 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1253                 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1254                         this, 0);
1255         }
1256 }
1257
1258 void GUIFormSpecMenu::parseSimpleField(parserData* data,
1259                 std::vector<std::string> &parts)
1260 {
1261         std::string name = parts[0];
1262         std::string label = parts[1];
1263         std::string default_val = parts[2];
1264
1265         core::rect<s32> rect;
1266
1267         if(data->explicit_size)
1268                 warningstream<<"invalid use of unpositioned \"field\" in inventory"<<std::endl;
1269
1270         v2s32 pos = getElementBasePos(false, nullptr);
1271         pos.Y = ((m_fields.size()+2)*60);
1272         v2s32 size = DesiredRect.getSize();
1273
1274         rect = core::rect<s32>(size.X / 2 - 150, pos.Y,
1275                         (size.X / 2 - 150) + 300, pos.Y + (m_btn_height*2));
1276
1277
1278         if(m_form_src)
1279                 default_val = m_form_src->resolveText(default_val);
1280
1281
1282         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1283
1284         FieldSpec spec(
1285                 name,
1286                 wlabel,
1287                 utf8_to_wide(unescape_string(default_val)),
1288                 258+m_fields.size()
1289         );
1290
1291         createTextField(data, spec, rect, false);
1292
1293         if (parts.size() >= 4) {
1294                 // TODO: remove after 2016-11-03
1295                 warningstream << "field/simple: use field_close_on_enter[name, enabled]" <<
1296                                 " instead of the 4th param" << std::endl;
1297                 field_close_on_enter[name] = is_yes(parts[3]);
1298         }
1299
1300         m_fields.push_back(spec);
1301 }
1302
1303 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1304                 const std::string &type)
1305 {
1306
1307         std::vector<std::string> v_pos = split(parts[0],',');
1308         std::vector<std::string> v_geom = split(parts[1],',');
1309         std::string name = parts[2];
1310         std::string label = parts[3];
1311         std::string default_val = parts[4];
1312
1313         MY_CHECKPOS(type,0);
1314         MY_CHECKGEOM(type,1);
1315
1316         v2s32 pos;
1317         v2s32 geom;
1318
1319         if (data->real_coordinates) {
1320                 pos = getRealCoordinateBasePos(false, v_pos);
1321                 geom = getRealCoordinateGeometry(v_geom);
1322         } else {
1323                 pos = getElementBasePos(false, &v_pos);
1324                 pos -= padding;
1325
1326                 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1327
1328                 if (type == "textarea")
1329                 {
1330                         geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1331                         pos.Y += m_btn_height;
1332                 }
1333                 else
1334                 {
1335                         pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1336                         pos.Y -= m_btn_height;
1337                         geom.Y = m_btn_height*2;
1338                 }
1339         }
1340
1341         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1342
1343         if(!data->explicit_size)
1344                 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1345
1346         if(m_form_src)
1347                 default_val = m_form_src->resolveText(default_val);
1348
1349
1350         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1351
1352         FieldSpec spec(
1353                 name,
1354                 wlabel,
1355                 utf8_to_wide(unescape_string(default_val)),
1356                 258+m_fields.size()
1357         );
1358
1359         createTextField(data, spec, rect, type == "textarea");
1360
1361         if (parts.size() >= 6) {
1362                 // TODO: remove after 2016-11-03
1363                 warningstream << "field/textarea: use field_close_on_enter[name, enabled]" <<
1364                                 " instead of the 6th param" << std::endl;
1365                 field_close_on_enter[name] = is_yes(parts[5]);
1366         }
1367
1368         m_fields.push_back(spec);
1369 }
1370
1371 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1372                 const std::string &type)
1373 {
1374         std::vector<std::string> parts = split(element,';');
1375
1376         if (parts.size() == 3 || parts.size() == 4) {
1377                 parseSimpleField(data,parts);
1378                 return;
1379         }
1380
1381         if ((parts.size() == 5) || (parts.size() == 6) ||
1382                 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1383         {
1384                 parseTextArea(data,parts,type);
1385                 return;
1386         }
1387         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1388 }
1389
1390 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1391 {
1392         std::vector<std::string> parts = split(element,';');
1393
1394         if ((parts.size() == 2) ||
1395                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1396         {
1397                 std::vector<std::string> v_pos = split(parts[0],',');
1398                 std::string text = parts[1];
1399
1400                 MY_CHECKPOS("label",0);
1401
1402                 if(!data->explicit_size)
1403                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1404
1405                 std::vector<std::string> lines = split(text, '\n');
1406
1407                 for (unsigned int i = 0; i != lines.size(); i++) {
1408                         std::wstring wlabel = unescape_translate(unescape_string(
1409                                 utf8_to_wide(lines[i])));
1410
1411                         core::rect<s32> rect;
1412
1413                         if (data->real_coordinates) {
1414                                 // Lines are spaced at the distance of 1/2 imgsize.
1415                                 // This alows lines that line up with the new elements
1416                                 // easily without sacrificing good line distance.  If
1417                                 // it was one whole imgsize, it would have too much
1418                                 // spacing.
1419                                 v2s32 pos = getRealCoordinateBasePos(false, v_pos);
1420
1421                                 // Labels are positioned by their center, not their top.
1422                                 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1423
1424                                 rect = core::rect<s32>(
1425                                         pos.X, pos.Y,
1426                                         pos.X + m_font->getDimension(wlabel.c_str()).Width,
1427                                         pos.Y + imgsize.Y);
1428
1429                         } else {
1430                                 // Lines are spaced at the nominal distance of
1431                                 // 2/5 inventory slot, even if the font doesn't
1432                                 // quite match that.  This provides consistent
1433                                 // form layout, at the expense of sometimes
1434                                 // having sub-optimal spacing for the font.
1435                                 // We multiply by 2 and then divide by 5, rather
1436                                 // than multiply by 0.4, to get exact results
1437                                 // in the integer cases: 0.4 is not exactly
1438                                 // representable in binary floating point.
1439
1440                                 v2s32 pos = getElementBasePos(false, nullptr);
1441                                 pos.X += stof(v_pos[0]) * spacing.X;
1442                                 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1443
1444                                 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1445
1446                                 rect = core::rect<s32>(
1447                                         pos.X, pos.Y - m_btn_height,
1448                                         pos.X + m_font->getDimension(wlabel.c_str()).Width,
1449                                         pos.Y + m_btn_height);
1450                         }
1451
1452                         FieldSpec spec(
1453                                 "",
1454                                 wlabel,
1455                                 L"",
1456                                 258+m_fields.size()
1457                         );
1458                         gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1459                                 spec.flabel.c_str(), rect, false, false, this, spec.fid);
1460                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1461
1462                         auto style = getStyleForElement("label", spec.fname);
1463                         e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1464                         e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1465
1466                         m_fields.push_back(spec);
1467                 }
1468
1469                 return;
1470         }
1471         errorstream << "Invalid label element(" << parts.size() << "): '" << element
1472                 << "'"  << std::endl;
1473 }
1474
1475 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1476 {
1477         std::vector<std::string> parts = split(element,';');
1478
1479         if ((parts.size() == 2) ||
1480                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1481         {
1482                 std::vector<std::string> v_pos = split(parts[0],',');
1483                 std::wstring text = unescape_translate(
1484                         unescape_string(utf8_to_wide(parts[1])));
1485
1486                 MY_CHECKPOS("vertlabel",1);
1487
1488                 v2s32 pos;
1489                 core::rect<s32> rect;
1490
1491                 if (data->real_coordinates) {
1492                         pos = getRealCoordinateBasePos(false, v_pos);
1493
1494                         // Vertlabels are positioned by center, not left.
1495                         pos.X -= imgsize.X / 2;
1496
1497                         // We use text.length + 1 because without it, the rect
1498                         // isn't quite tall enough and cuts off the text.
1499                         rect = core::rect<s32>(pos.X, pos.Y,
1500                                 pos.X + imgsize.X,
1501                                 pos.Y + font_line_height(m_font) *
1502                                 (text.length() + 1));
1503
1504                 } else {
1505                         pos = getElementBasePos(false, &v_pos);
1506
1507                         // As above, the length must be one longer. The width of
1508                         // the rect (15 pixels) seems rather arbitrary, but
1509                         // changing it might break something.
1510                         rect = core::rect<s32>(
1511                                 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1512                                 pos.X+15, pos.Y +
1513                                         font_line_height(m_font) *
1514                                         (text.length() + 1) +
1515                                         ((imgsize.Y/2) - m_btn_height));
1516                 }
1517
1518                 if(!data->explicit_size)
1519                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1520
1521                 std::wstring label;
1522
1523                 for (wchar_t i : text) {
1524                         label += i;
1525                         label += L"\n";
1526                 }
1527
1528                 FieldSpec spec(
1529                         "",
1530                         label,
1531                         L"",
1532                         258+m_fields.size()
1533                 );
1534                 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1535                         rect, false, false, this, spec.fid);
1536                 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1537
1538                 auto style = getStyleForElement("vertlabel", spec.fname, "label");
1539                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1540                 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1541
1542                 m_fields.push_back(spec);
1543                 return;
1544         }
1545         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1546 }
1547
1548 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1549                 const std::string &type)
1550 {
1551         std::vector<std::string> parts = split(element,';');
1552
1553         if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1554                 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1555         {
1556                 std::vector<std::string> v_pos = split(parts[0],',');
1557                 std::vector<std::string> v_geom = split(parts[1],',');
1558                 std::string image_name = parts[2];
1559                 std::string name = parts[3];
1560                 std::string label = parts[4];
1561
1562                 MY_CHECKPOS("imagebutton",0);
1563                 MY_CHECKGEOM("imagebutton",1);
1564
1565                 bool noclip     = false;
1566                 bool drawborder = true;
1567                 std::string pressed_image_name;
1568
1569                 if (parts.size() >= 7) {
1570                         if (parts[5] == "true")
1571                                 noclip = true;
1572                         if (parts[6] == "false")
1573                                 drawborder = false;
1574                 }
1575
1576                 if (parts.size() >= 8) {
1577                         pressed_image_name = parts[7];
1578                 }
1579
1580                 v2s32 pos;
1581                 v2s32 geom;
1582
1583                 if (data->real_coordinates) {
1584                         pos = getRealCoordinateBasePos(false, v_pos);
1585                         geom = getRealCoordinateGeometry(v_geom);
1586                 } else {
1587                         pos = getElementBasePos(false, &v_pos);
1588                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1589                         geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1590                 }
1591
1592                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1593                         pos.Y+geom.Y);
1594
1595                 if (!data->explicit_size)
1596                         warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1597
1598                 image_name = unescape_string(image_name);
1599                 pressed_image_name = unescape_string(pressed_image_name);
1600
1601                 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1602
1603                 FieldSpec spec(
1604                         name,
1605                         wlabel,
1606                         utf8_to_wide(image_name),
1607                         258+m_fields.size()
1608                 );
1609                 spec.ftype = f_Button;
1610                 if (type == "image_button_exit")
1611                         spec.is_exit = true;
1612
1613                 video::ITexture *texture = 0;
1614                 video::ITexture *pressed_texture = 0;
1615                 texture = m_tsrc->getTexture(image_name);
1616                 if (!pressed_image_name.empty())
1617                         pressed_texture = m_tsrc->getTexture(pressed_image_name);
1618                 else
1619                         pressed_texture = texture;
1620
1621                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1622
1623                 if (spec.fname == data->focused_fieldname) {
1624                         Environment->setFocus(e);
1625                 }
1626
1627                 auto style = getStyleForElement("image_button", spec.fname);
1628
1629                 e->setUseAlphaChannel(style.getBool(StyleSpec::ALPHA, true));
1630                 e->setImage(guiScalingImageButton(
1631                         Environment->getVideoDriver(), texture, geom.X, geom.Y));
1632                 e->setPressedImage(guiScalingImageButton(
1633                         Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
1634                 e->setScaleImage(true);
1635                 if (parts.size() >= 7) {
1636                         e->setNotClipped(noclip);
1637                         e->setDrawBorder(drawborder);
1638                 } else {
1639                         e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1640                         e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1641                 }
1642
1643                 m_fields.push_back(spec);
1644                 return;
1645         }
1646
1647         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1648 }
1649
1650 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1651 {
1652         std::vector<std::string> parts = split(element, ';');
1653
1654         if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
1655                 data->real_coordinates) || ((parts.size() > 6) &&
1656                 (m_formspec_version > FORMSPEC_API_VERSION)))
1657         {
1658                 std::vector<std::string> v_pos = split(parts[0],',');
1659
1660                 // If we're using real coordinates, add an extra field for height.
1661                 // Width is not here because tabs are the width of the text, and
1662                 // there's no reason to change that.
1663                 unsigned int i = 0;
1664                 std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
1665                 bool auto_width = true;
1666                 if (parts.size() == 7) {
1667                         i++;
1668
1669                         v_geom = split(parts[1], ',');
1670                         if (v_geom.size() == 1)
1671                                 v_geom.insert(v_geom.begin(), "1"); // Dummy value
1672                         else
1673                                 auto_width = false;
1674                 }
1675
1676                 std::string name = parts[i+1];
1677                 std::vector<std::string> buttons = split(parts[i+2], ',');
1678                 std::string str_index = parts[i+3];
1679                 bool show_background = true;
1680                 bool show_border = true;
1681                 int tab_index = stoi(str_index) - 1;
1682
1683                 MY_CHECKPOS("tabheader", 0);
1684
1685                 if (parts.size() == 6 + i) {
1686                         if (parts[4+i] == "true")
1687                                 show_background = false;
1688                         if (parts[5+i] == "false")
1689                                 show_border = false;
1690                 }
1691
1692                 FieldSpec spec(
1693                         name,
1694                         L"",
1695                         L"",
1696                         258+m_fields.size()
1697                 );
1698
1699                 spec.ftype = f_TabHeader;
1700
1701                 v2s32 pos;
1702                 v2s32 geom;
1703
1704                 if (data->real_coordinates) {
1705                         pos = getRealCoordinateBasePos(false, v_pos);
1706
1707                         geom = getRealCoordinateGeometry(v_geom);
1708                         pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
1709                         if (auto_width)
1710                                 geom.X = DesiredRect.getWidth(); // Set automatic width
1711
1712                         MY_CHECKGEOM("tabheader", 1);
1713                 } else {
1714                         v2f32 pos_f = pos_offset * spacing;
1715                         pos_f.X += stof(v_pos[0]) * spacing.X;
1716                         pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
1717                         pos = v2s32(pos_f.X, pos_f.Y);
1718
1719                         geom.Y = m_btn_height * 2;
1720                         geom.X = DesiredRect.getWidth();
1721                 }
1722
1723                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1724                                 pos.Y+geom.Y);
1725
1726                 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1727                                 show_background, show_border, spec.fid);
1728                 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1729                                 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1730                 e->setTabHeight(geom.Y);
1731
1732                 if (spec.fname == data->focused_fieldname) {
1733                         Environment->setFocus(e);
1734                 }
1735
1736                 auto style = getStyleForElement("tabheader", name);
1737                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
1738
1739                 for (const std::string &button : buttons) {
1740                         auto tab = e->addTab(unescape_translate(unescape_string(
1741                                 utf8_to_wide(button))).c_str(), -1);
1742                         if (style.isNotDefault(StyleSpec::BGCOLOR))
1743                                 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
1744
1745                         tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1746                 }
1747
1748                 if ((tab_index >= 0) &&
1749                                 (buttons.size() < INT_MAX) &&
1750                                 (tab_index < (int) buttons.size()))
1751                         e->setActiveTab(tab_index);
1752
1753                 m_fields.push_back(spec);
1754                 return;
1755         }
1756         errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
1757                         << element << "'"  << std::endl;
1758 }
1759
1760 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
1761 {
1762
1763         if (m_client == 0) {
1764                 warningstream << "invalid use of item_image_button with m_client==0"
1765                         << std::endl;
1766                 return;
1767         }
1768
1769         std::vector<std::string> parts = split(element,';');
1770
1771         if ((parts.size() == 5) ||
1772                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1773         {
1774                 std::vector<std::string> v_pos = split(parts[0],',');
1775                 std::vector<std::string> v_geom = split(parts[1],',');
1776                 std::string item_name = parts[2];
1777                 std::string name = parts[3];
1778                 std::string label = parts[4];
1779
1780                 label = unescape_string(label);
1781                 item_name = unescape_string(item_name);
1782
1783                 MY_CHECKPOS("itemimagebutton",0);
1784                 MY_CHECKGEOM("itemimagebutton",1);
1785
1786                 v2s32 pos;
1787                 v2s32 geom;
1788
1789                 if (data->real_coordinates) {
1790                         pos = getRealCoordinateBasePos(false, v_pos);
1791                         geom = getRealCoordinateGeometry(v_geom);
1792                 } else {
1793                         pos = getElementBasePos(false, &v_pos);
1794                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1795                         geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1796                 }
1797
1798                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1799
1800                 if(!data->explicit_size)
1801                         warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
1802
1803                 IItemDefManager *idef = m_client->idef();
1804                 ItemStack item;
1805                 item.deSerialize(item_name, idef);
1806
1807                 m_tooltips[name] =
1808                         TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
1809                                                 m_default_tooltip_bgcolor,
1810                                                 m_default_tooltip_color);
1811
1812                 FieldSpec spec(
1813                         name,
1814                         utf8_to_wide(label),
1815                         utf8_to_wide(item_name),
1816                         258 + m_fields.size()
1817                 );
1818
1819                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, L"");
1820
1821                 auto style = getStyleForElement("item_image_button", spec.fname, "image_button");
1822                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1823                 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1824
1825                 if (spec.fname == data->focused_fieldname) {
1826                         Environment->setFocus(e);
1827                 }
1828
1829                 spec.ftype = f_Button;
1830                 rect+=data->basepos-padding;
1831                 spec.rect=rect;
1832                 m_fields.push_back(spec);
1833
1834                 if (data->real_coordinates)
1835                         pos = getRealCoordinateBasePos(true, v_pos);
1836                 else
1837                         pos = getElementBasePos(true, &v_pos);
1838
1839                 m_itemimages.emplace_back("", item_name, e, pos, geom);
1840                 m_static_texts.emplace_back(utf8_to_wide(label), rect, e);
1841                 return;
1842         }
1843         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1844 }
1845
1846 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
1847 {
1848         std::vector<std::string> parts = split(element,';');
1849
1850         if ((parts.size() == 3) ||
1851                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
1852         {
1853                 std::vector<std::string> v_pos = split(parts[0],',');
1854                 std::vector<std::string> v_geom = split(parts[1],',');
1855
1856                 MY_CHECKPOS("box",0);
1857                 MY_CHECKGEOM("box",1);
1858
1859                 v2s32 pos;
1860                 v2s32 geom;
1861
1862                 if (data->real_coordinates) {
1863                         pos = getRealCoordinateBasePos(true, v_pos);
1864                         geom = getRealCoordinateGeometry(v_geom);
1865                 } else {
1866                         pos = getElementBasePos(true, &v_pos);
1867                         geom.X = stof(v_geom[0]) * spacing.X;
1868                         geom.Y = stof(v_geom[1]) * spacing.Y;
1869                 }
1870
1871                 video::SColor tmp_color;
1872
1873                 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
1874                         BoxDrawSpec spec(pos, geom, tmp_color);
1875
1876                         m_boxes.push_back(spec);
1877                 }
1878                 else {
1879                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1880                 }
1881                 return;
1882         }
1883         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1884 }
1885
1886 void GUIFormSpecMenu::parseBackgroundColor(parserData *data, const std::string &element)
1887 {
1888         std::vector<std::string> parts = split(element,';');
1889
1890         if (((parts.size() == 1) || (parts.size() == 2)) ||
1891                         ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) {
1892                 if (parts.size() == 1) {
1893                         parseColorString(parts[0], m_bgcolor, false);
1894                 } else if (parts.size() == 2) {
1895                         parseColorString(parts[0], m_fullscreen_bgcolor, false);
1896                         m_bgfullscreen = is_yes(parts[1]);
1897                 }
1898
1899                 return;
1900         }
1901
1902         errorstream << "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"
1903                         << std::endl;
1904 }
1905
1906 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
1907 {
1908         std::vector<std::string> parts = split(element,';');
1909
1910         if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
1911                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1912         {
1913                 parseColorString(parts[0], m_slotbg_n, false);
1914                 parseColorString(parts[1], m_slotbg_h, false);
1915
1916                 if (parts.size() >= 3) {
1917                         if (parseColorString(parts[2], m_slotbordercolor, false)) {
1918                                 m_slotborder = true;
1919                         }
1920                 }
1921                 if (parts.size() == 5) {
1922                         video::SColor tmp_color;
1923
1924                         if (parseColorString(parts[3], tmp_color, false))
1925                                 m_default_tooltip_bgcolor = tmp_color;
1926                         if (parseColorString(parts[4], tmp_color, false))
1927                                 m_default_tooltip_color = tmp_color;
1928                 }
1929                 return;
1930         }
1931         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1932 }
1933
1934 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
1935 {
1936         std::vector<std::string> parts = split(element,';');
1937         if (parts.size() < 2) {
1938                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
1939                                 << element << "'"  << std::endl;
1940                 return;
1941         }
1942
1943         // Get mode and check size
1944         bool rect_mode = parts[0].find(',') != std::string::npos;
1945         size_t base_size = rect_mode ? 3 : 2;
1946         if (parts.size() != base_size && parts.size() != base_size + 2) {
1947                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
1948                                 << element << "'"  << std::endl;
1949                 return;
1950         }
1951
1952         // Read colors
1953         video::SColor bgcolor = m_default_tooltip_bgcolor;
1954         video::SColor color   = m_default_tooltip_color;
1955         if (parts.size() == base_size + 2 &&
1956                         (!parseColorString(parts[base_size], bgcolor, false) ||
1957                                 !parseColorString(parts[base_size + 1], color, false))) {
1958                 errorstream << "Invalid color in tooltip element(" << parts.size()
1959                                 << "): '" << element << "'"  << std::endl;
1960                 return;
1961         }
1962
1963         // Make tooltip spec
1964         std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
1965         TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
1966
1967         // Add tooltip
1968         if (rect_mode) {
1969                 std::vector<std::string> v_pos  = split(parts[0], ',');
1970                 std::vector<std::string> v_geom = split(parts[1], ',');
1971
1972                 MY_CHECKPOS("tooltip", 0);
1973                 MY_CHECKGEOM("tooltip", 1);
1974
1975                 v2s32 pos;
1976                 v2s32 geom;
1977
1978                 if (data->real_coordinates) {
1979                         pos = getRealCoordinateBasePos(true, v_pos);
1980                         geom = getRealCoordinateGeometry(v_geom);
1981                 } else {
1982                         pos = getElementBasePos(true, &v_pos);
1983                         geom.X = stof(v_geom[0]) * spacing.X;
1984                         geom.Y = stof(v_geom[1]) * spacing.Y;
1985                 }
1986
1987                 irr::core::rect<s32> rect(pos, pos + geom);
1988                 m_tooltip_rects.emplace_back(rect, spec);
1989         } else {
1990                 m_tooltips[parts[0]] = spec;
1991         }
1992 }
1993
1994 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
1995 {
1996         //some prechecks
1997         if (data.empty())
1998                 return false;
1999
2000         std::vector<std::string> parts = split(data,'[');
2001
2002         if (parts.size() < 2) {
2003                 return false;
2004         }
2005
2006         if (parts[0] != "formspec_version") {
2007                 return false;
2008         }
2009
2010         if (is_number(parts[1])) {
2011                 m_formspec_version = mystoi(parts[1]);
2012                 return true;
2013         }
2014
2015         return false;
2016 }
2017
2018 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2019 {
2020         if (element.empty())
2021                 return false;
2022
2023         std::vector<std::string> parts = split(element,'[');
2024
2025         if (parts.size() < 2)
2026                 return false;
2027
2028         std::string type = trim(parts[0]);
2029         std::string description = trim(parts[1]);
2030
2031         if (type != "size" && type != "invsize")
2032                 return false;
2033
2034         if (type == "invsize")
2035                 log_deprecated("Deprecated formspec element \"invsize\" is used");
2036
2037         parseSize(data, description);
2038
2039         return true;
2040 }
2041
2042 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2043 {
2044         if (element.empty())
2045                 return false;
2046
2047         std::vector<std::string> parts = split(element, '[');
2048
2049         if (parts.size() != 2)
2050                 return false;
2051
2052         std::string type = trim(parts[0]);
2053         std::string description = trim(parts[1]);
2054
2055         if (type != "position")
2056                 return false;
2057
2058         parsePosition(data, description);
2059
2060         return true;
2061 }
2062
2063 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2064 {
2065         std::vector<std::string> parts = split(element, ',');
2066
2067         if (parts.size() == 2) {
2068                 data->offset.X = stof(parts[0]);
2069                 data->offset.Y = stof(parts[1]);
2070                 return;
2071         }
2072
2073         errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2074 }
2075
2076 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2077 {
2078         if (element.empty())
2079                 return false;
2080
2081         std::vector<std::string> parts = split(element, '[');
2082
2083         if (parts.size() != 2)
2084                 return false;
2085
2086         std::string type = trim(parts[0]);
2087         std::string description = trim(parts[1]);
2088
2089         if (type != "anchor")
2090                 return false;
2091
2092         parseAnchor(data, description);
2093
2094         return true;
2095 }
2096
2097 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2098 {
2099         std::vector<std::string> parts = split(element, ',');
2100
2101         if (parts.size() == 2) {
2102                 data->anchor.X = stof(parts[0]);
2103                 data->anchor.Y = stof(parts[1]);
2104                 return;
2105         }
2106
2107         errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2108                         << "'" << std::endl;
2109 }
2110
2111 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2112 {
2113         std::vector<std::string> parts = split(element, ';');
2114
2115         if (parts.size() < 2) {
2116                 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2117                                         << "'" << std::endl;
2118                 return false;
2119         }
2120
2121         std::string selector = trim(parts[0]);
2122         if (selector.empty()) {
2123                 errorstream << "Invalid style element (Selector required): '" << element
2124                                         << "'" << std::endl;
2125                 return false;
2126         }
2127
2128         StyleSpec spec;
2129
2130         for (size_t i = 1; i < parts.size(); i++) {
2131                 size_t equal_pos = parts[i].find('=');
2132                 if (equal_pos == std::string::npos) {
2133                         errorstream << "Invalid style element (Property missing value): '" << element
2134                                                 << "'" << std::endl;
2135                         return false;
2136                 }
2137
2138                 std::string propname = trim(parts[i].substr(0, equal_pos));
2139                 std::string value    = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2140
2141                 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2142
2143                 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2144                 if (prop == StyleSpec::NONE) {
2145                         if (property_warned.find(propname) != property_warned.end()) {
2146                                 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2147                                                 << element
2148                                                 << "'" << std::endl;
2149                                 property_warned.insert(propname);
2150                         }
2151                         return false;
2152                 }
2153
2154                 spec.set(prop, value);
2155         }
2156
2157         if (style_type) {
2158                 theme_by_type[selector] |= spec;
2159         } else {
2160                 theme_by_name[selector] |= spec;
2161         }
2162
2163         return true;
2164 }
2165
2166 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2167 {
2168         //some prechecks
2169         if (element.empty())
2170                 return;
2171
2172         if (parseVersionDirect(element))
2173                 return;
2174
2175         std::vector<std::string> parts = split(element,'[');
2176
2177         // ugly workaround to keep compatibility
2178         if (parts.size() > 2) {
2179                 if (trim(parts[0]) == "image") {
2180                         for (unsigned int i=2;i< parts.size(); i++) {
2181                                 parts[1] += "[" + parts[i];
2182                         }
2183                 }
2184                 else { return; }
2185         }
2186
2187         if (parts.size() < 2) {
2188                 return;
2189         }
2190
2191         std::string type = trim(parts[0]);
2192         std::string description = trim(parts[1]);
2193
2194         if (type == "container") {
2195                 parseContainer(data, description);
2196                 return;
2197         }
2198
2199         if (type == "container_end") {
2200                 parseContainerEnd(data);
2201                 return;
2202         }
2203
2204         if (type == "list") {
2205                 parseList(data, description);
2206                 return;
2207         }
2208
2209         if (type == "listring") {
2210                 parseListRing(data, description);
2211                 return;
2212         }
2213
2214         if (type == "checkbox") {
2215                 parseCheckbox(data, description);
2216                 return;
2217         }
2218
2219         if (type == "image") {
2220                 parseImage(data, description);
2221                 return;
2222         }
2223
2224         if (type == "item_image") {
2225                 parseItemImage(data, description);
2226                 return;
2227         }
2228
2229         if (type == "button" || type == "button_exit") {
2230                 parseButton(data, description, type);
2231                 return;
2232         }
2233
2234         if (type == "background" || type == "background9") {
2235                 parseBackground(data, description);
2236                 return;
2237         }
2238
2239         if (type == "tableoptions"){
2240                 parseTableOptions(data,description);
2241                 return;
2242         }
2243
2244         if (type == "tablecolumns"){
2245                 parseTableColumns(data,description);
2246                 return;
2247         }
2248
2249         if (type == "table"){
2250                 parseTable(data,description);
2251                 return;
2252         }
2253
2254         if (type == "textlist"){
2255                 parseTextList(data,description);
2256                 return;
2257         }
2258
2259         if (type == "dropdown"){
2260                 parseDropDown(data,description);
2261                 return;
2262         }
2263
2264         if (type == "field_close_on_enter") {
2265                 parseFieldCloseOnEnter(data, description);
2266                 return;
2267         }
2268
2269         if (type == "pwdfield") {
2270                 parsePwdField(data,description);
2271                 return;
2272         }
2273
2274         if ((type == "field") || (type == "textarea")){
2275                 parseField(data,description,type);
2276                 return;
2277         }
2278
2279         if (type == "label") {
2280                 parseLabel(data,description);
2281                 return;
2282         }
2283
2284         if (type == "vertlabel") {
2285                 parseVertLabel(data,description);
2286                 return;
2287         }
2288
2289         if (type == "item_image_button") {
2290                 parseItemImageButton(data,description);
2291                 return;
2292         }
2293
2294         if ((type == "image_button") || (type == "image_button_exit")) {
2295                 parseImageButton(data,description,type);
2296                 return;
2297         }
2298
2299         if (type == "tabheader") {
2300                 parseTabHeader(data,description);
2301                 return;
2302         }
2303
2304         if (type == "box") {
2305                 parseBox(data,description);
2306                 return;
2307         }
2308
2309         if (type == "bgcolor") {
2310                 parseBackgroundColor(data,description);
2311                 return;
2312         }
2313
2314         if (type == "listcolors") {
2315                 parseListColors(data,description);
2316                 return;
2317         }
2318
2319         if (type == "tooltip") {
2320                 parseTooltip(data,description);
2321                 return;
2322         }
2323
2324         if (type == "scrollbar") {
2325                 parseScrollBar(data, description);
2326                 return;
2327         }
2328
2329         if (type == "real_coordinates") {
2330                 data->real_coordinates = is_yes(description);
2331                 return;
2332         }
2333
2334         if (type == "style") {
2335                 parseStyle(data, description, false);
2336                 return;
2337         }
2338
2339         if (type == "style_type") {
2340                 parseStyle(data, description, true);
2341                 return;
2342         }
2343
2344         // Ignore others
2345         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2346                         << std::endl;
2347 }
2348
2349 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2350 {
2351         /* useless to regenerate without a screensize */
2352         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2353                 return;
2354         }
2355
2356         parserData mydata;
2357
2358         //preserve tables
2359         for (auto &m_table : m_tables) {
2360                 std::string tablename = m_table.first.fname;
2361                 GUITable *table = m_table.second;
2362                 mydata.table_dyndata[tablename] = table->getDynamicData();
2363         }
2364
2365         //set focus
2366         if (!m_focused_element.empty())
2367                 mydata.focused_fieldname = m_focused_element;
2368
2369         //preserve focus
2370         gui::IGUIElement *focused_element = Environment->getFocus();
2371         if (focused_element && focused_element->getParent() == this) {
2372                 s32 focused_id = focused_element->getID();
2373                 if (focused_id > 257) {
2374                         for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2375                                 if (field.fid == focused_id) {
2376                                         mydata.focused_fieldname = field.fname;
2377                                         break;
2378                                 }
2379                         }
2380                 }
2381         }
2382
2383         // Remove children
2384         removeChildren();
2385
2386         for (auto &table_it : m_tables) {
2387                 table_it.second->drop();
2388         }
2389
2390         mydata.size= v2s32(100,100);
2391         mydata.screensize = screensize;
2392         mydata.offset = v2f32(0.5f, 0.5f);
2393         mydata.anchor = v2f32(0.5f, 0.5f);
2394
2395         // Base position of contents of form
2396         mydata.basepos = getBasePos();
2397
2398         /* Convert m_init_draw_spec to m_inventorylists */
2399
2400         m_inventorylists.clear();
2401         m_images.clear();
2402         m_backgrounds.clear();
2403         m_itemimages.clear();
2404         m_tables.clear();
2405         m_checkboxes.clear();
2406         m_scrollbars.clear();
2407         m_fields.clear();
2408         m_boxes.clear();
2409         m_tooltips.clear();
2410         m_tooltip_rects.clear();
2411         m_inventory_rings.clear();
2412         m_static_texts.clear();
2413         m_dropdowns.clear();
2414         theme_by_name.clear();
2415         theme_by_type.clear();
2416
2417         m_bgfullscreen = false;
2418
2419         {
2420                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2421                 m_bgcolor = video::SColor(
2422                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2423                         clamp_u8(myround(formspec_bgcolor.X)),
2424                         clamp_u8(myround(formspec_bgcolor.Y)),
2425                         clamp_u8(myround(formspec_bgcolor.Z))
2426                 );
2427         }
2428
2429         {
2430                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2431                 m_fullscreen_bgcolor = video::SColor(
2432                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2433                         clamp_u8(myround(formspec_bgcolor.X)),
2434                         clamp_u8(myround(formspec_bgcolor.Y)),
2435                         clamp_u8(myround(formspec_bgcolor.Z))
2436                 );
2437         }
2438
2439         m_slotbg_n = video::SColor(255,128,128,128);
2440         m_slotbg_h = video::SColor(255,192,192,192);
2441
2442         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2443         m_default_tooltip_color = video::SColor(255,255,255,255);
2444
2445         m_slotbordercolor = video::SColor(200,0,0,0);
2446         m_slotborder = false;
2447
2448         // Add tooltip
2449         {
2450                 assert(!m_tooltip_element);
2451                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2452                 m_tooltip_element = gui::StaticText::add(Environment, L"",
2453                         core::rect<s32>(0, 0, 110, 18));
2454                 m_tooltip_element->enableOverrideColor(true);
2455                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2456                 m_tooltip_element->setDrawBackground(true);
2457                 m_tooltip_element->setDrawBorder(true);
2458                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2459                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2460                 m_tooltip_element->setWordWrap(false);
2461                 //we're not parent so no autograb for this one!
2462                 m_tooltip_element->grab();
2463         }
2464
2465         std::vector<std::string> elements = split(m_formspec_string,']');
2466         unsigned int i = 0;
2467
2468         /* try to read version from first element only */
2469         if (!elements.empty()) {
2470                 if (parseVersionDirect(elements[0])) {
2471                         i++;
2472                 }
2473         }
2474
2475         /* we need size first in order to calculate image scale */
2476         mydata.explicit_size = false;
2477         for (; i< elements.size(); i++) {
2478                 if (!parseSizeDirect(&mydata, elements[i])) {
2479                         break;
2480                 }
2481         }
2482
2483         /* "position" element is always after "size" element if it used */
2484         for (; i< elements.size(); i++) {
2485                 if (!parsePositionDirect(&mydata, elements[i])) {
2486                         break;
2487                 }
2488         }
2489
2490         /* "anchor" element is always after "position" (or  "size" element) if it used */
2491         for (; i< elements.size(); i++) {
2492                 if (!parseAnchorDirect(&mydata, elements[i])) {
2493                         break;
2494                 }
2495         }
2496
2497         /* "no_prepend" element is always after "position" (or  "size" element) if it used */
2498         bool enable_prepends = true;
2499         for (; i < elements.size(); i++) {
2500                 if (elements[i].empty())
2501                         break;
2502
2503                 std::vector<std::string> parts = split(elements[i], '[');
2504                 if (trim(parts[0]) == "no_prepend")
2505                         enable_prepends = false;
2506                 else
2507                         break;
2508         }
2509
2510         /* Copy of the "real_coordinates" element for after the form size. */
2511         mydata.real_coordinates = m_formspec_version >= 2;
2512         for (; i < elements.size(); i++) {
2513                 std::vector<std::string> parts = split(elements[i], '[');
2514                 std::string name = trim(parts[0]);
2515                 if (name != "real_coordinates" || parts.size() != 2)
2516                         break; // Invalid format
2517
2518                 mydata.real_coordinates = is_yes(trim(parts[1]));
2519         }
2520
2521         if (mydata.explicit_size) {
2522                 // compute scaling for specified form size
2523                 if (m_lock) {
2524                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2525                         v2u32 delta = current_screensize - m_lockscreensize;
2526
2527                         if (current_screensize.Y > m_lockscreensize.Y)
2528                                 delta.Y /= 2;
2529                         else
2530                                 delta.Y = 0;
2531
2532                         if (current_screensize.X > m_lockscreensize.X)
2533                                 delta.X /= 2;
2534                         else
2535                                 delta.X = 0;
2536
2537                         offset = v2s32(delta.X,delta.Y);
2538
2539                         mydata.screensize = m_lockscreensize;
2540                 } else {
2541                         offset = v2s32(0,0);
2542                 }
2543
2544                 double gui_scaling = g_settings->getFloat("gui_scaling");
2545                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2546
2547                 double use_imgsize;
2548                 if (m_lock) {
2549                         // In fixed-size mode, inventory image size
2550                         // is 0.53 inch multiplied by the gui_scaling
2551                         // config parameter.  This magic size is chosen
2552                         // to make the main menu (15.5 inventory images
2553                         // wide, including border) just fit into the
2554                         // default window (800 pixels wide) at 96 DPI
2555                         // and default scaling (1.00).
2556                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2557                 } else {
2558                         // In variable-size mode, we prefer to make the
2559                         // inventory image size 1/15 of screen height,
2560                         // multiplied by the gui_scaling config parameter.
2561                         // If the preferred size won't fit the whole
2562                         // form on the screen, either horizontally or
2563                         // vertically, then we scale it down to fit.
2564                         // (The magic numbers in the computation of what
2565                         // fits arise from the scaling factors in the
2566                         // following stanza, including the form border,
2567                         // help text space, and 0.1 inventory slot spare.)
2568                         // However, a minimum size is also set, that
2569                         // the image size can't be less than 0.3 inch
2570                         // multiplied by gui_scaling, even if this means
2571                         // the form doesn't fit the screen.
2572 #ifdef __ANDROID__
2573                         // For mobile devices these magic numbers are
2574                         // different and forms should always use the
2575                         // maximum screen space available.
2576                         double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
2577                         double fitx_imgsize = mydata.screensize.X /
2578                                 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
2579                         double fity_imgsize = mydata.screensize.Y /
2580                                 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
2581                         use_imgsize = MYMIN(prefer_imgsize,
2582                                         MYMIN(fitx_imgsize, fity_imgsize));
2583 #else
2584                         double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
2585                         double fitx_imgsize = mydata.screensize.X /
2586                                 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
2587                         double fity_imgsize = mydata.screensize.Y /
2588                                 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
2589                         double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2590                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2591                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2592                                 MYMIN(fitx_imgsize, fity_imgsize)));
2593 #endif
2594                 }
2595
2596                 // Everything else is scaled in proportion to the
2597                 // inventory image size.  The inventory slot spacing
2598                 // is 5/4 image size horizontally and 15/13 image size
2599                 // vertically.  The padding around the form (incorporating
2600                 // the border of the outer inventory slots) is 3/8
2601                 // image size.  Font height (baseline to baseline)
2602                 // is 2/5 vertical inventory slot spacing, and button
2603                 // half-height is 7/8 of font height.
2604                 imgsize = v2s32(use_imgsize, use_imgsize);
2605                 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2606                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2607                 m_btn_height = use_imgsize*15.0/13 * 0.35;
2608
2609                 m_font = g_fontengine->getFont();
2610
2611                 if (mydata.real_coordinates) {
2612                         mydata.size = v2s32(
2613                                 mydata.invsize.X*imgsize.X,
2614                                 mydata.invsize.Y*imgsize.Y
2615                         );
2616                 } else {
2617                         mydata.size = v2s32(
2618                                 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2619                                 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2620                         );
2621                 }
2622
2623                 DesiredRect = mydata.rect = core::rect<s32>(
2624                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2625                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2626                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2627                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2628                 );
2629         } else {
2630                 // Non-size[] form must consist only of text fields and
2631                 // implicit "Proceed" button.  Use default font, and
2632                 // temporary form size which will be recalculated below.
2633                 m_font = g_fontengine->getFont();
2634                 m_btn_height = font_line_height(m_font) * 0.875;
2635                 DesiredRect = core::rect<s32>(
2636                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2637                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2638                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2639                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2640                 );
2641         }
2642         recalculateAbsolutePosition(false);
2643         mydata.basepos = getBasePos();
2644         m_tooltip_element->setOverrideFont(m_font);
2645
2646         gui::IGUISkin *skin = Environment->getSkin();
2647         sanity_check(skin);
2648         gui::IGUIFont *old_font = skin->getFont();
2649         skin->setFont(m_font);
2650
2651         pos_offset = v2f32();
2652
2653         if (enable_prepends) {
2654                 // Backup the coordinates so that prepends can use the coordinates of choice.
2655                 bool rc_backup = mydata.real_coordinates;
2656                 u16 version_backup = m_formspec_version;
2657                 mydata.real_coordinates = false; // Old coordinates by default.
2658
2659                 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
2660                 for (const auto &element : prepend_elements)
2661                         parseElement(&mydata, element);
2662
2663                 m_formspec_version = version_backup;
2664                 mydata.real_coordinates = rc_backup; // Restore coordinates
2665         }
2666
2667         for (; i< elements.size(); i++) {
2668                 parseElement(&mydata, elements[i]);
2669         }
2670
2671         if (!container_stack.empty()) {
2672                 errorstream << "Invalid formspec string: container was never closed!"
2673                         << std::endl;
2674         }
2675
2676         // If there are fields without explicit size[], add a "Proceed"
2677         // button and adjust size to fit all the fields.
2678         if (!m_fields.empty() && !mydata.explicit_size) {
2679                 mydata.rect = core::rect<s32>(
2680                                 mydata.screensize.X/2 - 580/2,
2681                                 mydata.screensize.Y/2 - 300/2,
2682                                 mydata.screensize.X/2 + 580/2,
2683                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
2684                 );
2685                 DesiredRect = mydata.rect;
2686                 recalculateAbsolutePosition(false);
2687                 mydata.basepos = getBasePos();
2688
2689                 {
2690                         v2s32 pos = mydata.basepos;
2691                         pos.Y = ((m_fields.size()+2)*60);
2692
2693                         v2s32 size = DesiredRect.getSize();
2694                         mydata.rect =
2695                                         core::rect<s32>(size.X/2-70, pos.Y,
2696                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2697                         const wchar_t *text = wgettext("Proceed");
2698                         Environment->addButton(mydata.rect, this, 257, text);
2699                         delete[] text;
2700                 }
2701
2702         }
2703
2704         //set initial focus if parser didn't set it
2705         focused_element = Environment->getFocus();
2706         if (!focused_element
2707                         || !isMyChild(focused_element)
2708                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2709                 setInitialFocus();
2710
2711         skin->setFont(old_font);
2712 }
2713
2714 #ifdef __ANDROID__
2715 bool GUIFormSpecMenu::getAndroidUIInput()
2716 {
2717         if (!hasAndroidUIInput())
2718                 return false;
2719
2720         std::string fieldname = m_jni_field_name;
2721         m_jni_field_name.clear();
2722
2723         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2724                         iter != m_fields.end(); ++iter) {
2725
2726                 if (iter->fname != fieldname) {
2727                         continue;
2728                 }
2729                 IGUIElement* tochange = getElementFromId(iter->fid);
2730
2731                 if (tochange == 0) {
2732                         return false;
2733                 }
2734
2735                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2736                         return false;
2737                 }
2738
2739                 std::string text = porting::getInputDialogValue();
2740
2741                 ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
2742         }
2743         return false;
2744 }
2745 #endif
2746
2747 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2748 {
2749         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2750
2751         for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
2752                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2753                         s32 item_i = i + s.start_item_i;
2754
2755                         s32 x;
2756                         s32 y;
2757                         if (s.real_coordinates) {
2758                                 x = (i%s.geom.X) * (imgsize.X * 1.25);
2759                                 y = (i/s.geom.X) * (imgsize.Y * 1.25);
2760                         } else {
2761                                 x = (i%s.geom.X) * spacing.X;
2762                                 y = (i/s.geom.X) * spacing.Y;
2763                         }
2764                         v2s32 p0(x,y);
2765                         core::rect<s32> rect = imgrect + s.pos + p0;
2766                         if(rect.isPointInside(p))
2767                         {
2768                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2769                         }
2770                 }
2771         }
2772
2773         return ItemSpec(InventoryLocation(), "", -1);
2774 }
2775
2776 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer,
2777                 bool &item_hovered)
2778 {
2779         video::IVideoDriver* driver = Environment->getVideoDriver();
2780
2781         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2782         if(!inv){
2783                 warningstream<<"GUIFormSpecMenu::drawList(): "
2784                                 <<"The inventory location "
2785                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2786                                 <<std::endl;
2787                 return;
2788         }
2789         InventoryList *ilist = inv->getList(s.listname);
2790         if(!ilist){
2791                 warningstream<<"GUIFormSpecMenu::drawList(): "
2792                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2793                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2794                                 <<std::endl;
2795                 return;
2796         }
2797
2798         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2799
2800         for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) {
2801                 s32 item_i = i + s.start_item_i;
2802                 if (item_i >= (s32)ilist->getSize())
2803                         break;
2804
2805                 s32 x;
2806                 s32 y;
2807                 if (s.real_coordinates) {
2808                         x = (i%s.geom.X) * (imgsize.X * 1.25);
2809                         y = (i/s.geom.X) * (imgsize.Y * 1.25);
2810                 } else {
2811                         x = (i%s.geom.X) * spacing.X;
2812                         y = (i/s.geom.X) * spacing.Y;
2813                 }
2814                 v2s32 p(x,y);
2815                 core::rect<s32> rect = imgrect + s.pos + p;
2816                 ItemStack item = ilist->getItem(item_i);
2817
2818                 bool selected = m_selected_item
2819                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2820                         && m_selected_item->listname == s.listname
2821                         && m_selected_item->i == item_i;
2822                 bool hovering = rect.isPointInside(m_pointer);
2823                 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
2824                         (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
2825
2826                 if (layer == 0) {
2827                         if (hovering) {
2828                                 item_hovered = true;
2829                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2830                         } else {
2831                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2832                         }
2833                 }
2834
2835                 //Draw inv slot borders
2836                 if (m_slotborder) {
2837                         s32 x1 = rect.UpperLeftCorner.X;
2838                         s32 y1 = rect.UpperLeftCorner.Y;
2839                         s32 x2 = rect.LowerRightCorner.X;
2840                         s32 y2 = rect.LowerRightCorner.Y;
2841                         s32 border = 1;
2842                         driver->draw2DRectangle(m_slotbordercolor,
2843                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2844                                                                 v2s32(x2 + border, y1)), NULL);
2845                         driver->draw2DRectangle(m_slotbordercolor,
2846                                 core::rect<s32>(v2s32(x1 - border, y2),
2847                                                                 v2s32(x2 + border, y2 + border)), NULL);
2848                         driver->draw2DRectangle(m_slotbordercolor,
2849                                 core::rect<s32>(v2s32(x1 - border, y1),
2850                                                                 v2s32(x1, y2)), NULL);
2851                         driver->draw2DRectangle(m_slotbordercolor,
2852                                 core::rect<s32>(v2s32(x2, y1),
2853                                                                 v2s32(x2 + border, y2)), NULL);
2854                 }
2855
2856                 if (layer == 1) {
2857                         if (selected)
2858                                 item.takeItem(m_selected_amount);
2859
2860                         if (!item.empty()) {
2861                                 // Draw item stack
2862                                 drawItemStack(driver, m_font, item,
2863                                         rect, &AbsoluteClippingRect, m_client,
2864                                         rotation_kind);
2865                                 // Draw tooltip
2866                                 if (hovering && !m_selected_item) {
2867                                         std::string tooltip = item.getDescription(m_client->idef());
2868                                         if (m_tooltip_append_itemname)
2869                                                 tooltip += "\n[" + item.name + "]";
2870                                         showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
2871                                                         m_default_tooltip_bgcolor);
2872                                 }
2873                         }
2874                 }
2875         }
2876 }
2877
2878 void GUIFormSpecMenu::drawSelectedItem()
2879 {
2880         video::IVideoDriver* driver = Environment->getVideoDriver();
2881
2882         if (!m_selected_item) {
2883                 drawItemStack(driver, m_font, ItemStack(),
2884                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
2885                         NULL, m_client, IT_ROT_DRAGGED);
2886                 return;
2887         }
2888
2889         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2890         sanity_check(inv);
2891         InventoryList *list = inv->getList(m_selected_item->listname);
2892         sanity_check(list);
2893         ItemStack stack = list->getItem(m_selected_item->i);
2894         stack.count = m_selected_amount;
2895
2896         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2897         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2898         rect.constrainTo(driver->getViewPort());
2899         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
2900 }
2901
2902 void GUIFormSpecMenu::drawMenu()
2903 {
2904         if (m_form_src) {
2905                 const std::string &newform = m_form_src->getForm();
2906                 if (newform != m_formspec_string) {
2907                         m_formspec_string = newform;
2908                         regenerateGui(m_screensize_old);
2909                 }
2910         }
2911
2912         gui::IGUISkin* skin = Environment->getSkin();
2913         sanity_check(skin != NULL);
2914         gui::IGUIFont *old_font = skin->getFont();
2915         skin->setFont(m_font);
2916
2917         updateSelectedItem();
2918
2919         video::IVideoDriver* driver = Environment->getVideoDriver();
2920
2921         v2u32 screenSize = driver->getScreenSize();
2922         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
2923
2924         if (m_bgfullscreen)
2925                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
2926         driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2927
2928         m_tooltip_element->setVisible(false);
2929
2930         for (const auto &pair : m_tooltip_rects) {
2931                 if (pair.first.isPointInside(m_pointer)) {
2932                         const std::wstring &text = pair.second.tooltip;
2933                         if (!text.empty()) {
2934                                 showTooltip(text, pair.second.color, pair.second.bgcolor);
2935                                 break;
2936                         }
2937                 }
2938         }
2939
2940         /*
2941                 Draw backgrounds
2942         */
2943         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_backgrounds) {
2944                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2945
2946                 if (texture != 0) {
2947                         // Image size on screen
2948                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2949                         // Image rectangle on screen
2950                         core::rect<s32> rect = imgrect + spec.pos;
2951                         // Middle rect for 9-slicing
2952                         core::rect<s32> middle = spec.middle;
2953
2954                         if (spec.clip) {
2955                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2956                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2957                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2958                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2959                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2960                         }
2961
2962                         if (middle.getArea() == 0) {
2963                                 const video::SColor color(255, 255, 255, 255);
2964                                 const video::SColor colors[] = {color, color, color, color};
2965                                 draw2DImageFilterScaled(driver, texture, rect,
2966                                                 core::rect<s32>(core::position2d<s32>(0, 0),
2967                                                                 core::dimension2di(texture->getOriginalSize())),
2968                                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2969                         } else {
2970                                 // `-x` is interpreted as `w - x`
2971                                 if (middle.LowerRightCorner.X < 0) {
2972                                         middle.LowerRightCorner.X += texture->getOriginalSize().Width;
2973                                 }
2974                                 if (middle.LowerRightCorner.Y < 0) {
2975                                         middle.LowerRightCorner.Y += texture->getOriginalSize().Height;
2976                                 }
2977                                 draw2DImage9Slice(driver, texture, rect, middle);
2978                         }
2979                 } else {
2980                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2981                         errorstream << "\t" << spec.name << std::endl;
2982                 }
2983         }
2984
2985         /*
2986                 Draw Boxes
2987         */
2988         for (const GUIFormSpecMenu::BoxDrawSpec &spec : m_boxes) {
2989                 irr::video::SColor todraw = spec.color;
2990
2991                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2992                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2993
2994                 driver->draw2DRectangle(todraw, rect, 0);
2995         }
2996
2997         /*
2998                 Call base class
2999         */
3000         gui::IGUIElement::draw();
3001
3002         /*
3003                 Draw images
3004         */
3005         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_images) {
3006                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
3007
3008                 if (texture != 0) {
3009                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
3010                         // Image size on screen
3011                         core::rect<s32> imgrect;
3012
3013                         if (spec.scale)
3014                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
3015                         else {
3016
3017                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
3018                         }
3019                         // Image rectangle on screen
3020                         core::rect<s32> rect = imgrect + spec.pos;
3021                         const video::SColor color(255,255,255,255);
3022                         const video::SColor colors[] = {color,color,color,color};
3023                         draw2DImageFilterScaled(driver, texture, rect,
3024                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
3025                                 NULL/*&AbsoluteClippingRect*/, colors, true);
3026                 }
3027                 else {
3028                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
3029                         errorstream << "\t" << spec.name << std::endl;
3030                 }
3031         }
3032
3033         /*
3034                 Draw item images
3035         */
3036         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_itemimages) {
3037                 if (m_client == 0)
3038                         break;
3039
3040                 IItemDefManager *idef = m_client->idef();
3041                 ItemStack item;
3042                 item.deSerialize(spec.item_name, idef);
3043                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
3044                 // Viewport rectangle on screen
3045                 core::rect<s32> rect = imgrect + spec.pos;
3046                 if (spec.parent_button && spec.parent_button->isPressed()) {
3047 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
3048                         rect += core::dimension2d<s32>(
3049                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
3050 #else
3051                         rect += core::dimension2d<s32>(
3052                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
3053                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
3054 #endif
3055                 }
3056                 drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect,
3057                                 m_client, IT_ROT_NONE);
3058         }
3059
3060         /*
3061                 Draw items
3062                 Layer 0: Item slot rectangles
3063                 Layer 1: Item images; prepare tooltip
3064         */
3065         bool item_hovered = false;
3066         for (int layer = 0; layer < 2; layer++) {
3067                 for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
3068                         drawList(spec, layer, item_hovered);
3069                 }
3070         }
3071         if (!item_hovered) {
3072                 drawItemStack(driver, m_font, ItemStack(),
3073                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3074                         NULL, m_client, IT_ROT_HOVERED);
3075         }
3076
3077 /* TODO find way to show tooltips on touchscreen */
3078 #ifndef HAVE_TOUCHSCREENGUI
3079         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3080 #endif
3081
3082         /*
3083                 Draw static text elements
3084         */
3085         for (const GUIFormSpecMenu::StaticTextSpec &spec : m_static_texts) {
3086                 core::rect<s32> rect = spec.rect;
3087                 if (spec.parent_button && spec.parent_button->isPressed()) {
3088 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
3089                         rect += core::dimension2d<s32>(
3090                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
3091 #else
3092                         // Use image offset instead of text's because its a bit smaller
3093                         // and fits better, also TEXT_OFFSET_X is always 0
3094                         rect += core::dimension2d<s32>(
3095                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
3096                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
3097 #endif
3098                 }
3099                 video::SColor color(255, 255, 255, 255);
3100                 m_font->draw(spec.text.c_str(), rect, color, true, true, &rect);
3101         }
3102
3103         /*
3104                 Draw fields/buttons tooltips
3105         */
3106         gui::IGUIElement *hovered =
3107                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3108
3109         if (hovered != NULL) {
3110                 s32 id = hovered->getID();
3111
3112                 u64 delta = 0;
3113                 if (id == -1) {
3114                         m_old_tooltip_id = id;
3115                 } else {
3116                         if (id == m_old_tooltip_id) {
3117                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3118                         } else {
3119                                 m_hovered_time = porting::getTimeMs();
3120                                 m_old_tooltip_id = id;
3121                         }
3122                 }
3123
3124                 // Find and update the current tooltip
3125                 if (id != -1 && delta >= m_tooltip_show_delay) {
3126                         for (const FieldSpec &field : m_fields) {
3127
3128                                 if (field.fid != id)
3129                                         continue;
3130
3131                                 const std::wstring &text = m_tooltips[field.fname].tooltip;
3132                                 if (!text.empty())
3133                                         showTooltip(text, m_tooltips[field.fname].color,
3134                                                 m_tooltips[field.fname].bgcolor);
3135
3136                                 break;
3137                         }
3138                 }
3139         }
3140
3141         m_tooltip_element->draw();
3142
3143         /*
3144                 Draw dragged item stack
3145         */
3146         drawSelectedItem();
3147
3148         skin->setFont(old_font);
3149 }
3150
3151
3152 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3153         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3154 {
3155         const std::wstring ntext = translate_string(text);
3156         m_tooltip_element->setOverrideColor(color);
3157         m_tooltip_element->setBackgroundColor(bgcolor);
3158         setStaticText(m_tooltip_element, ntext.c_str());
3159
3160         // Tooltip size and offset
3161         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3162 #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
3163         std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
3164         s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
3165 #else
3166         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3167 #endif
3168         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3169         int tooltip_offset_x = m_btn_height;
3170         int tooltip_offset_y = m_btn_height;
3171 #ifdef __ANDROID__
3172         tooltip_offset_x *= 3;
3173         tooltip_offset_y  = 0;
3174         if (m_pointer.X > (s32)screenSize.X / 2)
3175                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3176 #endif
3177
3178         // Calculate and set the tooltip position
3179         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3180         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3181         if (tooltip_x + tooltip_width > (s32)screenSize.X)
3182                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
3183         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3184                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3185
3186         m_tooltip_element->setRelativePosition(
3187                 core::rect<s32>(
3188                         core::position2d<s32>(tooltip_x, tooltip_y),
3189                         core::dimension2d<s32>(tooltip_width, tooltip_height)
3190                 )
3191         );
3192
3193         // Display the tooltip
3194         m_tooltip_element->setVisible(true);
3195         bringToFront(m_tooltip_element);
3196 }
3197
3198 void GUIFormSpecMenu::updateSelectedItem()
3199 {
3200         verifySelectedItem();
3201
3202         // If craftresult is nonempty and nothing else is selected, select it now.
3203         if (!m_selected_item) {
3204                 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3205                         if (s.listname != "craftpreview")
3206                                 continue;
3207
3208                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3209                         if (!inv)
3210                                 continue;
3211
3212                         InventoryList *list = inv->getList("craftresult");
3213
3214                         if (!list || list->getSize() == 0)
3215                                 continue;
3216
3217                         const ItemStack &item = list->getItem(0);
3218                         if (item.empty())
3219                                 continue;
3220
3221                         // Grab selected item from the crafting result list
3222                         m_selected_item = new ItemSpec;
3223                         m_selected_item->inventoryloc = s.inventoryloc;
3224                         m_selected_item->listname = "craftresult";
3225                         m_selected_item->i = 0;
3226                         m_selected_amount = item.count;
3227                         m_selected_dragging = false;
3228                         break;
3229                 }
3230         }
3231
3232         // If craftresult is selected, keep the whole stack selected
3233         if (m_selected_item && m_selected_item->listname == "craftresult")
3234                 m_selected_amount = verifySelectedItem().count;
3235 }
3236
3237 ItemStack GUIFormSpecMenu::verifySelectedItem()
3238 {
3239         // If the selected stack has become empty for some reason, deselect it.
3240         // If the selected stack has become inaccessible, deselect it.
3241         // If the selected stack has become smaller, adjust m_selected_amount.
3242         // Return the selected stack.
3243
3244         if(m_selected_item)
3245         {
3246                 if(m_selected_item->isValid())
3247                 {
3248                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3249                         if(inv)
3250                         {
3251                                 InventoryList *list = inv->getList(m_selected_item->listname);
3252                                 if(list && (u32) m_selected_item->i < list->getSize())
3253                                 {
3254                                         ItemStack stack = list->getItem(m_selected_item->i);
3255                                         if (!m_selected_swap.empty()) {
3256                                                 if (m_selected_swap.name == stack.name &&
3257                                                                 m_selected_swap.count == stack.count)
3258                                                         m_selected_swap.clear();
3259                                         } else {
3260                                                 m_selected_amount = std::min(m_selected_amount, stack.count);
3261                                         }
3262
3263                                         if (!stack.empty())
3264                                                 return stack;
3265                                 }
3266                         }
3267                 }
3268
3269                 // selection was not valid
3270                 delete m_selected_item;
3271                 m_selected_item = NULL;
3272                 m_selected_amount = 0;
3273                 m_selected_dragging = false;
3274         }
3275         return ItemStack();
3276 }
3277
3278 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3279 {
3280         if(m_text_dst)
3281         {
3282                 StringMap fields;
3283
3284                 if (quitmode == quit_mode_accept) {
3285                         fields["quit"] = "true";
3286                 }
3287
3288                 if (quitmode == quit_mode_cancel) {
3289                         fields["quit"] = "true";
3290                         m_text_dst->gotText(fields);
3291                         return;
3292                 }
3293
3294                 if (current_keys_pending.key_down) {
3295                         fields["key_down"] = "true";
3296                         current_keys_pending.key_down = false;
3297                 }
3298
3299                 if (current_keys_pending.key_up) {
3300                         fields["key_up"] = "true";
3301                         current_keys_pending.key_up = false;
3302                 }
3303
3304                 if (current_keys_pending.key_enter) {
3305                         fields["key_enter"] = "true";
3306                         current_keys_pending.key_enter = false;
3307                 }
3308
3309                 if (!current_field_enter_pending.empty()) {
3310                         fields["key_enter_field"] = current_field_enter_pending;
3311                         current_field_enter_pending = "";
3312                 }
3313
3314                 if (current_keys_pending.key_escape) {
3315                         fields["key_escape"] = "true";
3316                         current_keys_pending.key_escape = false;
3317                 }
3318
3319                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3320                         if(s.send) {
3321                                 std::string name = s.fname;
3322                                 if (s.ftype == f_Button) {
3323                                         fields[name] = wide_to_utf8(s.flabel);
3324                                 } else if (s.ftype == f_Table) {
3325                                         GUITable *table = getTable(s.fname);
3326                                         if (table) {
3327                                                 fields[name] = table->checkEvent();
3328                                         }
3329                                 }
3330                                 else if(s.ftype == f_DropDown) {
3331                                         // no dynamic cast possible due to some distributions shipped
3332                                         // without rtti support in irrlicht
3333                                         IGUIElement * element = getElementFromId(s.fid);
3334                                         gui::IGUIComboBox *e = NULL;
3335                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3336                                                 e = static_cast<gui::IGUIComboBox*>(element);
3337                                         }
3338                                         s32 selected = e->getSelected();
3339                                         if (selected >= 0) {
3340                                                 std::vector<std::string> *dropdown_values =
3341                                                         getDropDownValues(s.fname);
3342                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3343                                                         fields[name] = (*dropdown_values)[selected];
3344                                                 }
3345                                         }
3346                                 }
3347                                 else if (s.ftype == f_TabHeader) {
3348                                         // no dynamic cast possible due to some distributions shipped
3349                                         // without rttzi support in irrlicht
3350                                         IGUIElement * element = getElementFromId(s.fid);
3351                                         gui::IGUITabControl *e = NULL;
3352                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3353                                                 e = static_cast<gui::IGUITabControl *>(element);
3354                                         }
3355
3356                                         if (e != 0) {
3357                                                 std::stringstream ss;
3358                                                 ss << (e->getActiveTab() +1);
3359                                                 fields[name] = ss.str();
3360                                         }
3361                                 }
3362                                 else if (s.ftype == f_CheckBox) {
3363                                         // no dynamic cast possible due to some distributions shipped
3364                                         // without rtti support in irrlicht
3365                                         IGUIElement * element = getElementFromId(s.fid);
3366                                         gui::IGUICheckBox *e = NULL;
3367                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3368                                                 e = static_cast<gui::IGUICheckBox*>(element);
3369                                         }
3370
3371                                         if (e != 0) {
3372                                                 if (e->isChecked())
3373                                                         fields[name] = "true";
3374                                                 else
3375                                                         fields[name] = "false";
3376                                         }
3377                                 }
3378                                 else if (s.ftype == f_ScrollBar) {
3379                                         // no dynamic cast possible due to some distributions shipped
3380                                         // without rtti support in irrlicht
3381                                         IGUIElement * element = getElementFromId(s.fid);
3382                                         gui::IGUIScrollBar *e = NULL;
3383                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
3384                                                 e = static_cast<gui::IGUIScrollBar*>(element);
3385                                         }
3386
3387                                         if (e != 0) {
3388                                                 std::stringstream os;
3389                                                 os << e->getPos();
3390                                                 if (s.fdefault == L"Changed")
3391                                                         fields[name] = "CHG:" + os.str();
3392                                                 else
3393                                                         fields[name] = "VAL:" + os.str();
3394                                         }
3395                                 }
3396                                 else
3397                                 {
3398                                         IGUIElement* e = getElementFromId(s.fid);
3399                                         if(e != NULL) {
3400                                                 fields[name] = wide_to_utf8(e->getText());
3401                                         }
3402                                 }
3403                         }
3404                 }
3405
3406                 m_text_dst->gotText(fields);
3407         }
3408 }
3409
3410 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
3411 {
3412         while(tocheck != NULL) {
3413                 if (tocheck == parent) {
3414                         return true;
3415                 }
3416                 tocheck = tocheck->getParent();
3417         }
3418         return false;
3419 }
3420
3421 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3422 {
3423         // The IGUITabControl renders visually using the skin's selected
3424         // font, which we override for the duration of form drawing,
3425         // but computes tab hotspots based on how it would have rendered
3426         // using the font that is selected at the time of button release.
3427         // To make these two consistent, temporarily override the skin's
3428         // font while the IGUITabControl is processing the event.
3429         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3430                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3431                 s32 x = event.MouseInput.X;
3432                 s32 y = event.MouseInput.Y;
3433                 gui::IGUIElement *hovered =
3434                         Environment->getRootGUIElement()->getElementFromPoint(
3435                                 core::position2d<s32>(x, y));
3436                 if (hovered && isMyChild(hovered) &&
3437                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3438                         gui::IGUISkin* skin = Environment->getSkin();
3439                         sanity_check(skin != NULL);
3440                         gui::IGUIFont *old_font = skin->getFont();
3441                         skin->setFont(m_font);
3442                         bool retval = hovered->OnEvent(event);
3443                         skin->setFont(old_font);
3444                         return retval;
3445                 }
3446         }
3447
3448         // Fix Esc/Return key being eaten by checkboxen and tables
3449         if(event.EventType==EET_KEY_INPUT_EVENT) {
3450                 KeyPress kp(event.KeyInput);
3451                 if (kp == EscapeKey || kp == CancelKey
3452                                 || kp == getKeySetting("keymap_inventory")
3453                                 || event.KeyInput.Key==KEY_RETURN) {
3454                         gui::IGUIElement *focused = Environment->getFocus();
3455                         if (focused && isMyChild(focused) &&
3456                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
3457                                         focused->getType() == gui::EGUIET_CHECK_BOX) &&
3458                                         (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3459                                         event.KeyInput.Key != KEY_RETURN)) {
3460                                 OnEvent(event);
3461                                 return true;
3462                         }
3463                 }
3464         }
3465         // Mouse wheel events: send to hovered element instead of focused
3466         if(event.EventType==EET_MOUSE_INPUT_EVENT
3467                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
3468                 s32 x = event.MouseInput.X;
3469                 s32 y = event.MouseInput.Y;
3470                 gui::IGUIElement *hovered =
3471                         Environment->getRootGUIElement()->getElementFromPoint(
3472                                 core::position2d<s32>(x, y));
3473                 if (hovered && isMyChild(hovered)) {
3474                         hovered->OnEvent(event);
3475                         return true;
3476                 }
3477         }
3478
3479         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3480                 s32 x = event.MouseInput.X;
3481                 s32 y = event.MouseInput.Y;
3482                 gui::IGUIElement *hovered =
3483                         Environment->getRootGUIElement()->getElementFromPoint(
3484                                 core::position2d<s32>(x, y));
3485                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3486                         m_old_tooltip_id = -1;
3487                 }
3488                 if (!isChild(hovered,this)) {
3489                         if (DoubleClickDetection(event)) {
3490                                 return true;
3491                         }
3492                 }
3493         }
3494
3495         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3496                 /* TODO add a check like:
3497                 if (event.JoystickEvent != joystick_we_listen_for)
3498                         return false;
3499                 */
3500                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3501                 if (handled) {
3502                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
3503                                 tryClose();
3504                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3505                                 if (m_allowclose) {
3506                                         acceptInput(quit_mode_accept);
3507                                         quitMenu();
3508                                 }
3509                         }
3510                 }
3511                 return handled;
3512         }
3513
3514         return GUIModalMenu::preprocessEvent(event);
3515 }
3516
3517 /******************************************************************************/
3518 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3519 {
3520         /* The following code is for capturing double-clicks of the mouse button
3521          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3522          * -- which closes the form -- under some circumstances.
3523          *
3524          * There have been many github issues reporting this as a bug even though it
3525          * was an intended feature.  For this reason, remapping the double-click as
3526          * an ESC must be explicitly set when creating this class via the
3527          * /p remap_dbl_click parameter of the constructor.
3528          */
3529
3530         if (!m_remap_dbl_click)
3531                 return false;
3532
3533         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3534                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3535                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3536
3537                 m_doubleclickdetect[1].pos  = m_pointer;
3538                 m_doubleclickdetect[1].time = porting::getTimeMs();
3539         }
3540         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3541                 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3542                 if (delta > 400) {
3543                         return false;
3544                 }
3545
3546                 double squaredistance =
3547                                 m_doubleclickdetect[0].pos
3548                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3549
3550                 if (squaredistance > (30*30)) {
3551                         return false;
3552                 }
3553
3554                 SEvent* translated = new SEvent();
3555                 assert(translated != 0);
3556                 //translate doubleclick to escape
3557                 memset(translated, 0, sizeof(SEvent));
3558                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3559                 translated->KeyInput.Key         = KEY_ESCAPE;
3560                 translated->KeyInput.Control     = false;
3561                 translated->KeyInput.Shift       = false;
3562                 translated->KeyInput.PressedDown = true;
3563                 translated->KeyInput.Char        = 0;
3564                 OnEvent(*translated);
3565
3566                 // no need to send the key up event as we're already deleted
3567                 // and no one else did notice this event
3568                 delete translated;
3569                 return true;
3570         }
3571
3572         return false;
3573 }
3574
3575 void GUIFormSpecMenu::tryClose()
3576 {
3577         if (m_allowclose) {
3578                 doPause = false;
3579                 acceptInput(quit_mode_cancel);
3580                 quitMenu();
3581         } else {
3582                 m_text_dst->gotText(L"MenuQuit");
3583         }
3584 }
3585
3586 enum ButtonEventType : u8
3587 {
3588         BET_LEFT,
3589         BET_RIGHT,
3590         BET_MIDDLE,
3591         BET_WHEEL_UP,
3592         BET_WHEEL_DOWN,
3593         BET_UP,
3594         BET_DOWN,
3595         BET_MOVE,
3596         BET_OTHER
3597 };
3598
3599 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3600 {
3601         if (event.EventType==EET_KEY_INPUT_EVENT) {
3602                 KeyPress kp(event.KeyInput);
3603                 if (event.KeyInput.PressedDown && (
3604                                 (kp == EscapeKey) || (kp == CancelKey) ||
3605                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3606                         tryClose();
3607                         return true;
3608                 }
3609
3610                 if (m_client != NULL && event.KeyInput.PressedDown &&
3611                                 (kp == getKeySetting("keymap_screenshot"))) {
3612                         m_client->makeScreenshot();
3613                 }
3614                 if (event.KeyInput.PressedDown &&
3615                         (event.KeyInput.Key==KEY_RETURN ||
3616                          event.KeyInput.Key==KEY_UP ||
3617                          event.KeyInput.Key==KEY_DOWN)
3618                         ) {
3619                         switch (event.KeyInput.Key) {
3620                                 case KEY_RETURN:
3621                                         current_keys_pending.key_enter = true;
3622                                         break;
3623                                 case KEY_UP:
3624                                         current_keys_pending.key_up = true;
3625                                         break;
3626                                 case KEY_DOWN:
3627                                         current_keys_pending.key_down = true;
3628                                         break;
3629                                 break;
3630                                 default:
3631                                         //can't happen at all!
3632                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3633                                         break;
3634                         }
3635                         if (current_keys_pending.key_enter && m_allowclose) {
3636                                 acceptInput(quit_mode_accept);
3637                                 quitMenu();
3638                         } else {
3639                                 acceptInput();
3640                         }
3641                         return true;
3642                 }
3643
3644         }
3645
3646         /* Mouse event other than movement, or crossing the border of inventory
3647           field while holding right mouse button
3648          */
3649         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3650                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3651                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3652                           event.MouseInput.isRightPressed() &&
3653                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3654
3655                 // Get selected item and hovered/clicked item (s)
3656
3657                 m_old_tooltip_id = -1;
3658                 updateSelectedItem();
3659                 ItemSpec s = getItemAtPos(m_pointer);
3660
3661                 Inventory *inv_selected = NULL;
3662                 Inventory *inv_s = NULL;
3663                 InventoryList *list_s = NULL;
3664
3665                 if (m_selected_item) {
3666                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3667                         sanity_check(inv_selected);
3668                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3669                 }
3670
3671                 u32 s_count = 0;
3672
3673                 if (s.isValid())
3674                 do { // breakable
3675                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3676
3677                         if (!inv_s) {
3678                                 errorstream << "InventoryMenu: The selected inventory location "
3679                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3680                                                 << std::endl;
3681                                 s.i = -1;  // make it invalid again
3682                                 break;
3683                         }
3684
3685                         list_s = inv_s->getList(s.listname);
3686                         if (list_s == NULL) {
3687                                 verbosestream << "InventoryMenu: The selected inventory list \""
3688                                                 << s.listname << "\" does not exist" << std::endl;
3689                                 s.i = -1;  // make it invalid again
3690                                 break;
3691                         }
3692
3693                         if ((u32)s.i >= list_s->getSize()) {
3694                                 infostream << "InventoryMenu: The selected inventory list \""
3695                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
3696                                                 << list_s->getSize() << ")" << std::endl;
3697                                 s.i = -1;  // make it invalid again
3698                                 break;
3699                         }
3700
3701                         s_count = list_s->getItem(s.i).count;
3702                 } while(0);
3703
3704                 bool identical = m_selected_item && s.isValid() &&
3705                         (inv_selected == inv_s) &&
3706                         (m_selected_item->listname == s.listname) &&
3707                         (m_selected_item->i == s.i);
3708
3709                 ButtonEventType button = BET_LEFT;
3710                 ButtonEventType updown = BET_OTHER;
3711                 switch (event.MouseInput.Event) {
3712                 case EMIE_LMOUSE_PRESSED_DOWN:
3713                         button = BET_LEFT; updown = BET_DOWN;
3714                         break;
3715                 case EMIE_RMOUSE_PRESSED_DOWN:
3716                         button = BET_RIGHT; updown = BET_DOWN;
3717                         break;
3718                 case EMIE_MMOUSE_PRESSED_DOWN:
3719                         button = BET_MIDDLE; updown = BET_DOWN;
3720                         break;
3721                 case EMIE_MOUSE_WHEEL:
3722                         button = (event.MouseInput.Wheel > 0) ?
3723                                 BET_WHEEL_UP : BET_WHEEL_DOWN;
3724                         updown = BET_DOWN;
3725                         break;
3726                 case EMIE_LMOUSE_LEFT_UP:
3727                         button = BET_LEFT; updown = BET_UP;
3728                         break;
3729                 case EMIE_RMOUSE_LEFT_UP:
3730                         button = BET_RIGHT; updown = BET_UP;
3731                         break;
3732                 case EMIE_MMOUSE_LEFT_UP:
3733                         button = BET_MIDDLE; updown = BET_UP;
3734                         break;
3735                 case EMIE_MOUSE_MOVED:
3736                         updown = BET_MOVE;
3737                         break;
3738                 default:
3739                         break;
3740                 }
3741
3742                 // Set this number to a positive value to generate a move action
3743                 // from m_selected_item to s.
3744                 u32 move_amount = 0;
3745
3746                 // Set this number to a positive value to generate a move action
3747                 // from s to the next inventory ring.
3748                 u32 shift_move_amount = 0;
3749
3750                 // Set this number to a positive value to generate a drop action
3751                 // from m_selected_item.
3752                 u32 drop_amount = 0;
3753
3754                 // Set this number to a positive value to generate a craft action at s.
3755                 u32 craft_amount = 0;
3756
3757                 switch (updown) {
3758                 case BET_DOWN:
3759                         // Some mouse button has been pressed
3760
3761                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3762                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3763
3764                         m_selected_dragging = false;
3765
3766                         if (s.isValid() && s.listname == "craftpreview") {
3767                                 // Craft preview has been clicked: craft
3768                                 craft_amount = (button == BET_MIDDLE ? 10 : 1);
3769                         } else if (!m_selected_item) {
3770                                 if (s_count && button != BET_WHEEL_UP) {
3771                                         // Non-empty stack has been clicked: select or shift-move it
3772                                         m_selected_item = new ItemSpec(s);
3773
3774                                         u32 count;
3775                                         if (button == BET_RIGHT)
3776                                                 count = (s_count + 1) / 2;
3777                                         else if (button == BET_MIDDLE)
3778                                                 count = MYMIN(s_count, 10);
3779                                         else if (button == BET_WHEEL_DOWN)
3780                                                 count = 1;
3781                                         else  // left
3782                                                 count = s_count;
3783
3784                                         if (!event.MouseInput.Shift) {
3785                                                 // no shift: select item
3786                                                 m_selected_amount = count;
3787                                                 m_selected_dragging = button != BET_WHEEL_DOWN;
3788                                                 m_auto_place = false;
3789                                         } else {
3790                                                 // shift pressed: move item, right click moves 1
3791                                                 shift_move_amount = button == BET_RIGHT ? 1 : count;
3792                                         }
3793                                 }
3794                         } else { // m_selected_item != NULL
3795                                 assert(m_selected_amount >= 1);
3796
3797                                 if (s.isValid()) {
3798                                         // Clicked a slot: move
3799                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
3800                                                 move_amount = 1;
3801                                         else if (button == BET_MIDDLE)
3802                                                 move_amount = MYMIN(m_selected_amount, 10);
3803                                         else if (button == BET_LEFT)
3804                                                 move_amount = m_selected_amount;
3805                                         // else wheeldown
3806
3807                                         if (identical) {
3808                                                 if (button == BET_WHEEL_DOWN) {
3809                                                         if (m_selected_amount < s_count)
3810                                                                 ++m_selected_amount;
3811                                                 } else {
3812                                                         if (move_amount >= m_selected_amount)
3813                                                                 m_selected_amount = 0;
3814                                                         else
3815                                                                 m_selected_amount -= move_amount;
3816                                                         move_amount = 0;
3817                                                 }
3818                                         }
3819                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
3820                                                 && button != BET_WHEEL_DOWN) {
3821                                         // Clicked outside of the window: drop
3822                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
3823                                                 drop_amount = 1;
3824                                         else if (button == BET_MIDDLE)
3825                                                 drop_amount = MYMIN(m_selected_amount, 10);
3826                                         else  // left
3827                                                 drop_amount = m_selected_amount;
3828                                 }
3829                         }
3830                 break;
3831                 case BET_UP:
3832                         // Some mouse button has been released
3833
3834                         //infostream<<"Mouse button "<<button<<" released at p=("
3835                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3836
3837                         if (m_selected_dragging && m_selected_item) {
3838                                 if (s.isValid()) {
3839                                         if (!identical) {
3840                                                 // Dragged to different slot: move all selected
3841                                                 move_amount = m_selected_amount;
3842                                         }
3843                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3844                                         // Dragged outside of window: drop all selected
3845                                         drop_amount = m_selected_amount;
3846                                 }
3847                         }
3848
3849                         m_selected_dragging = false;
3850                         // Keep track of whether the mouse button be released
3851                         // One click is drag without dropping. Click + release
3852                         // + click changes to drop item when moved mode
3853                         if (m_selected_item)
3854                                 m_auto_place = true;
3855                 break;
3856                 case BET_MOVE:
3857                         // Mouse has been moved and rmb is down and mouse pointer just
3858                         // entered a new inventory field (checked in the entry-if, this
3859                         // is the only action here that is generated by mouse movement)
3860                         if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
3861                                 // Move 1 item
3862                                 // TODO: middle mouse to move 10 items might be handy
3863                                 if (m_auto_place) {
3864                                         // Only move an item if the destination slot is empty
3865                                         // or contains the same item type as what is going to be
3866                                         // moved
3867                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3868                                         InventoryList *list_to = list_s;
3869                                         assert(list_from && list_to);
3870                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3871                                         ItemStack stack_to = list_to->getItem(s.i);
3872                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3873                                                 move_amount = 1;
3874                                 }
3875                         }
3876                 break;
3877                 default:
3878                         break;
3879                 }
3880
3881                 // Possibly send inventory action to server
3882                 if (move_amount > 0) {
3883                         // Send IAction::Move
3884
3885                         assert(m_selected_item && m_selected_item->isValid());
3886                         assert(s.isValid());
3887
3888                         assert(inv_selected && inv_s);
3889                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3890                         InventoryList *list_to = list_s;
3891                         assert(list_from && list_to);
3892                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3893                         ItemStack stack_to = list_to->getItem(s.i);
3894
3895                         // Check how many items can be moved
3896                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3897                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
3898                         bool move = true;
3899                         // If source stack cannot be added to destination stack at all,
3900                         // they are swapped
3901                         if (leftover.count == stack_from.count &&
3902                                         leftover.name == stack_from.name) {
3903
3904                                 if (m_selected_swap.empty()) {
3905                                         m_selected_amount = stack_to.count;
3906                                         m_selected_dragging = false;
3907
3908                                         // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
3909                                         // Skip next validation checks due async inventory calls
3910                                         m_selected_swap = stack_to;
3911                                 } else {
3912                                         move = false;
3913                                 }
3914                         }
3915                         // Source stack goes fully into destination stack
3916                         else if (leftover.empty()) {
3917                                 m_selected_amount -= move_amount;
3918                         }
3919                         // Source stack goes partly into destination stack
3920                         else {
3921                                 move_amount -= leftover.count;
3922                                 m_selected_amount -= move_amount;
3923                         }
3924
3925                         if (move) {
3926                                 infostream << "Handing IAction::Move to manager" << std::endl;
3927                                 IMoveAction *a = new IMoveAction();
3928                                 a->count = move_amount;
3929                                 a->from_inv = m_selected_item->inventoryloc;
3930                                 a->from_list = m_selected_item->listname;
3931                                 a->from_i = m_selected_item->i;
3932                                 a->to_inv = s.inventoryloc;
3933                                 a->to_list = s.listname;
3934                                 a->to_i = s.i;
3935                                 m_invmgr->inventoryAction(a);
3936                         }
3937                 } else if (shift_move_amount > 0) {
3938                         u32 mis = m_inventory_rings.size();
3939                         u32 i = 0;
3940                         for (; i < mis; i++) {
3941                                 const ListRingSpec &sp = m_inventory_rings[i];
3942                                 if (sp.inventoryloc == s.inventoryloc
3943                                                 && sp.listname == s.listname)
3944                                         break;
3945                         }
3946                         do {
3947                                 if (i >= mis) // if not found
3948                                         break;
3949                                 u32 to_inv_ind = (i + 1) % mis;
3950                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
3951                                 InventoryList *list_from = list_s;
3952                                 if (!s.isValid())
3953                                         break;
3954                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
3955                                 if (!inv_to)
3956                                         break;
3957                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
3958                                 if (!list_to)
3959                                         break;
3960                                 ItemStack stack_from = list_from->getItem(s.i);
3961                                 assert(shift_move_amount <= stack_from.count);
3962
3963                                 infostream << "Handing IAction::Move to manager" << std::endl;
3964                                 IMoveAction *a = new IMoveAction();
3965                                 a->count = shift_move_amount;
3966                                 a->from_inv = s.inventoryloc;
3967                                 a->from_list = s.listname;
3968                                 a->from_i = s.i;
3969                                 a->to_inv = to_inv_sp.inventoryloc;
3970                                 a->to_list = to_inv_sp.listname;
3971                                 a->move_somewhere = true;
3972                                 m_invmgr->inventoryAction(a);
3973                         } while (0);
3974                 } else if (drop_amount > 0) {
3975                         // Send IAction::Drop
3976
3977                         assert(m_selected_item && m_selected_item->isValid());
3978                         assert(inv_selected);
3979                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3980                         assert(list_from);
3981                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3982
3983                         // Check how many items can be dropped
3984                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3985                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3986                         m_selected_amount -= drop_amount;
3987
3988                         infostream << "Handing IAction::Drop to manager" << std::endl;
3989                         IDropAction *a = new IDropAction();
3990                         a->count = drop_amount;
3991                         a->from_inv = m_selected_item->inventoryloc;
3992                         a->from_list = m_selected_item->listname;
3993                         a->from_i = m_selected_item->i;
3994                         m_invmgr->inventoryAction(a);
3995                 } else if (craft_amount > 0) {
3996                         assert(s.isValid());
3997
3998                         // if there are no items selected or the selected item
3999                         // belongs to craftresult list, proceed with crafting
4000                         if (m_selected_item == NULL ||
4001                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4002
4003                                 assert(inv_s);
4004
4005                                 // Send IACTION_CRAFT
4006                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4007                                 ICraftAction *a = new ICraftAction();
4008                                 a->count = craft_amount;
4009                                 a->craft_inv = s.inventoryloc;
4010                                 m_invmgr->inventoryAction(a);
4011                         }
4012                 }
4013
4014                 // If m_selected_amount has been decreased to zero, deselect
4015                 if (m_selected_amount == 0) {
4016                         m_selected_swap.clear();
4017                         delete m_selected_item;
4018                         m_selected_item = NULL;
4019                         m_selected_amount = 0;
4020                         m_selected_dragging = false;
4021                 }
4022                 m_old_pointer = m_pointer;
4023         }
4024         if (event.EventType == EET_GUI_EVENT) {
4025
4026                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4027                                 && isVisible()) {
4028                         // find the element that was clicked
4029                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4030                                 if ((s.ftype == f_TabHeader) &&
4031                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4032                                         s.send = true;
4033                                         acceptInput();
4034                                         s.send = false;
4035                                         return true;
4036                                 }
4037                         }
4038                 }
4039                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4040                                 && isVisible()) {
4041                         if (!canTakeFocus(event.GUIEvent.Element)) {
4042                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4043                                                 <<std::endl;
4044                                 // Returning true disables focus change
4045                                 return true;
4046                         }
4047                 }
4048                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4049                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4050                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4051                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4052                         unsigned int btn_id = event.GUIEvent.Caller->getID();
4053
4054                         if (btn_id == 257) {
4055                                 if (m_allowclose) {
4056                                         acceptInput(quit_mode_accept);
4057                                         quitMenu();
4058                                 } else {
4059                                         acceptInput();
4060                                         m_text_dst->gotText(L"ExitButton");
4061                                 }
4062                                 // quitMenu deallocates menu
4063                                 return true;
4064                         }
4065
4066                         // find the element that was clicked
4067                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4068                                 // if its a button, set the send field so
4069                                 // lua knows which button was pressed
4070                                 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
4071                                                 s.fid == event.GUIEvent.Caller->getID()) {
4072                                         s.send = true;
4073                                         if (s.is_exit) {
4074                                                 if (m_allowclose) {
4075                                                         acceptInput(quit_mode_accept);
4076                                                         quitMenu();
4077                                                 } else {
4078                                                         m_text_dst->gotText(L"ExitButton");
4079                                                 }
4080                                                 return true;
4081                                         }
4082
4083                                         acceptInput(quit_mode_no);
4084                                         s.send = false;
4085                                         return true;
4086
4087                                 } else if ((s.ftype == f_DropDown) &&
4088                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4089                                         // only send the changed dropdown
4090                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4091                                                 if (s2.ftype == f_DropDown) {
4092                                                         s2.send = false;
4093                                                 }
4094                                         }
4095                                         s.send = true;
4096                                         acceptInput(quit_mode_no);
4097
4098                                         // revert configuration to make sure dropdowns are sent on
4099                                         // regular button click
4100                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4101                                                 if (s2.ftype == f_DropDown) {
4102                                                         s2.send = true;
4103                                                 }
4104                                         }
4105                                         return true;
4106                                 } else if ((s.ftype == f_ScrollBar) &&
4107                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4108                                         s.fdefault = L"Changed";
4109                                         acceptInput(quit_mode_no);
4110                                         s.fdefault = L"";
4111                                 }
4112                         }
4113                 }
4114
4115                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4116                         if (event.GUIEvent.Caller->getID() > 257) {
4117                                 bool close_on_enter = true;
4118                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4119                                         if (s.ftype == f_Unknown &&
4120                                                         s.fid == event.GUIEvent.Caller->getID()) {
4121                                                 current_field_enter_pending = s.fname;
4122                                                 std::unordered_map<std::string, bool>::const_iterator it =
4123                                                         field_close_on_enter.find(s.fname);
4124                                                 if (it != field_close_on_enter.end())
4125                                                         close_on_enter = (*it).second;
4126
4127                                                 break;
4128                                         }
4129                                 }
4130
4131                                 if (m_allowclose && close_on_enter) {
4132                                         current_keys_pending.key_enter = true;
4133                                         acceptInput(quit_mode_accept);
4134                                         quitMenu();
4135                                 } else {
4136                                         current_keys_pending.key_enter = true;
4137                                         acceptInput();
4138                                 }
4139                                 // quitMenu deallocates menu
4140                                 return true;
4141                         }
4142                 }
4143
4144                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4145                         int current_id = event.GUIEvent.Caller->getID();
4146                         if (current_id > 257) {
4147                                 // find the element that was clicked
4148                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4149                                         // if it's a table, set the send field
4150                                         // so lua knows which table was changed
4151                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
4152                                                 s.send = true;
4153                                                 acceptInput();
4154                                                 s.send=false;
4155                                         }
4156                                 }
4157                                 return true;
4158                         }
4159                 }
4160         }
4161
4162         return Parent ? Parent->OnEvent(event) : false;
4163 }
4164
4165 /**
4166  * get name of element by element id
4167  * @param id of element
4168  * @return name string or empty string
4169  */
4170 std::string GUIFormSpecMenu::getNameByID(s32 id)
4171 {
4172         for (FieldSpec &spec : m_fields) {
4173                 if (spec.fid == id) {
4174                         return spec.fname;
4175                 }
4176         }
4177         return "";
4178 }
4179
4180 /**
4181  * get label of element by id
4182  * @param id of element
4183  * @return label string or empty string
4184  */
4185 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4186 {
4187         for (FieldSpec &spec : m_fields) {
4188                 if (spec.fid == id) {
4189                         return spec.flabel;
4190                 }
4191         }
4192         return L"";
4193 }
4194
4195 StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
4196                 const std::string &name, const std::string &parent_type) {
4197         StyleSpec ret;
4198
4199         if (!parent_type.empty()) {
4200                 auto it = theme_by_type.find(parent_type);
4201                 if (it != theme_by_type.end()) {
4202                         ret |= it->second;
4203                 }
4204         }
4205
4206         auto it = theme_by_type.find(type);
4207         if (it != theme_by_type.end()) {
4208                 ret |= it->second;
4209         }
4210
4211         it = theme_by_name.find(name);
4212         if (it != theme_by_name.end()) {
4213                 ret |= it->second;
4214         }
4215
4216         return ret;
4217 }