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