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