]> git.lizzy.rs Git - dragonfireclient.git/blob - src/gui/guiFormSpecMenu.cpp
Don't override the FGIMG style property if the image parameter is null
[dragonfireclient.git] / src / gui / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <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                 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
1839
1840                 if (spec.fname == data->focused_fieldname) {
1841                         Environment->setFocus(e);
1842                 }
1843
1844                 auto style = getStyleForElement("image_button", spec.fname);
1845                 e->setFromStyle(style, m_tsrc);
1846
1847                 // We explicitly handle these arguments *after* the style properties in
1848                 // order to override them if they are provided
1849                 if (!image_name.empty())
1850                 {
1851                         video::ITexture *texture = m_tsrc->getTexture(image_name);
1852                         e->setForegroundImage(guiScalingImageButton(
1853                                 Environment->getVideoDriver(), texture, geom.X, geom.Y));
1854                 }
1855                 if (!pressed_image_name.empty()) {
1856                         video::ITexture *pressed_texture = m_tsrc->getTexture(pressed_image_name);
1857                         e->setPressedForegroundImage(guiScalingImageButton(
1858                                                 Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
1859                 }
1860                 e->setScaleImage(true);
1861
1862                 if (parts.size() >= 7) {
1863                         e->setNotClipped(noclip);
1864                         e->setDrawBorder(drawborder);
1865                 }
1866
1867                 m_fields.push_back(spec);
1868                 return;
1869         }
1870
1871         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1872 }
1873
1874 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1875 {
1876         std::vector<std::string> parts = split(element, ';');
1877
1878         if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
1879                 data->real_coordinates) || ((parts.size() > 6) &&
1880                 (m_formspec_version > FORMSPEC_API_VERSION)))
1881         {
1882                 std::vector<std::string> v_pos = split(parts[0],',');
1883
1884                 // If we're using real coordinates, add an extra field for height.
1885                 // Width is not here because tabs are the width of the text, and
1886                 // there's no reason to change that.
1887                 unsigned int i = 0;
1888                 std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
1889                 bool auto_width = true;
1890                 if (parts.size() == 7) {
1891                         i++;
1892
1893                         v_geom = split(parts[1], ',');
1894                         if (v_geom.size() == 1)
1895                                 v_geom.insert(v_geom.begin(), "1"); // Dummy value
1896                         else
1897                                 auto_width = false;
1898                 }
1899
1900                 std::string name = parts[i+1];
1901                 std::vector<std::string> buttons = split(parts[i+2], ',');
1902                 std::string str_index = parts[i+3];
1903                 bool show_background = true;
1904                 bool show_border = true;
1905                 int tab_index = stoi(str_index) - 1;
1906
1907                 MY_CHECKPOS("tabheader", 0);
1908
1909                 if (parts.size() == 6 + i) {
1910                         if (parts[4+i] == "true")
1911                                 show_background = false;
1912                         if (parts[5+i] == "false")
1913                                 show_border = false;
1914                 }
1915
1916                 FieldSpec spec(
1917                         name,
1918                         L"",
1919                         L"",
1920                         258 + m_fields.size()
1921                 );
1922
1923                 spec.ftype = f_TabHeader;
1924
1925                 v2s32 pos;
1926                 v2s32 geom;
1927
1928                 if (data->real_coordinates) {
1929                         pos = getRealCoordinateBasePos(v_pos);
1930
1931                         geom = getRealCoordinateGeometry(v_geom);
1932                         pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
1933                         if (auto_width)
1934                                 geom.X = DesiredRect.getWidth(); // Set automatic width
1935
1936                         MY_CHECKGEOM("tabheader", 1);
1937                 } else {
1938                         v2f32 pos_f = pos_offset * spacing;
1939                         pos_f.X += stof(v_pos[0]) * spacing.X;
1940                         pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
1941                         pos = v2s32(pos_f.X, pos_f.Y);
1942
1943                         geom.Y = m_btn_height * 2;
1944                         geom.X = DesiredRect.getWidth();
1945                 }
1946
1947                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1948                                 pos.Y+geom.Y);
1949
1950                 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1951                                 show_background, show_border, spec.fid);
1952                 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1953                                 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1954                 e->setTabHeight(geom.Y);
1955
1956                 if (spec.fname == data->focused_fieldname) {
1957                         Environment->setFocus(e);
1958                 }
1959
1960                 auto style = getStyleForElement("tabheader", name);
1961                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
1962
1963                 for (const std::string &button : buttons) {
1964                         auto tab = e->addTab(unescape_translate(unescape_string(
1965                                 utf8_to_wide(button))).c_str(), -1);
1966                         if (style.isNotDefault(StyleSpec::BGCOLOR))
1967                                 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
1968
1969                         tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1970                 }
1971
1972                 if ((tab_index >= 0) &&
1973                                 (buttons.size() < INT_MAX) &&
1974                                 (tab_index < (int) buttons.size()))
1975                         e->setActiveTab(tab_index);
1976
1977                 m_fields.push_back(spec);
1978                 return;
1979         }
1980         errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
1981                         << element << "'"  << std::endl;
1982 }
1983
1984 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
1985 {
1986
1987         if (m_client == 0) {
1988                 warningstream << "invalid use of item_image_button with m_client==0"
1989                         << std::endl;
1990                 return;
1991         }
1992
1993         std::vector<std::string> parts = split(element,';');
1994
1995         if ((parts.size() == 5) ||
1996                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1997         {
1998                 std::vector<std::string> v_pos = split(parts[0],',');
1999                 std::vector<std::string> v_geom = split(parts[1],',');
2000                 std::string item_name = parts[2];
2001                 std::string name = parts[3];
2002                 std::string label = parts[4];
2003
2004                 label = unescape_string(label);
2005                 item_name = unescape_string(item_name);
2006
2007                 MY_CHECKPOS("itemimagebutton",0);
2008                 MY_CHECKGEOM("itemimagebutton",1);
2009
2010                 v2s32 pos;
2011                 v2s32 geom;
2012
2013                 if (data->real_coordinates) {
2014                         pos = getRealCoordinateBasePos(v_pos);
2015                         geom = getRealCoordinateGeometry(v_geom);
2016                 } else {
2017                         pos = getElementBasePos(&v_pos);
2018                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2019                         geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2020                 }
2021
2022                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2023
2024                 if(!data->explicit_size)
2025                         warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2026
2027                 IItemDefManager *idef = m_client->idef();
2028                 ItemStack item;
2029                 item.deSerialize(item_name, idef);
2030
2031                 m_tooltips[name] =
2032                         TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2033                                                 m_default_tooltip_bgcolor,
2034                                                 m_default_tooltip_color);
2035
2036                 // the spec for the button
2037                 FieldSpec spec_btn(
2038                         name,
2039                         utf8_to_wide(label),
2040                         utf8_to_wide(item_name),
2041                         258 + m_fields.size(),
2042                         2
2043                 );
2044
2045                 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment, rect, this, spec_btn.fid, spec_btn.flabel.c_str(), item_name, m_client);
2046
2047                 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2048                 e_btn->setFromStyle(style, m_tsrc);
2049
2050                 if (spec_btn.fname == data->focused_fieldname) {
2051                         Environment->setFocus(e_btn);
2052                 }
2053
2054                 spec_btn.ftype = f_Button;
2055                 rect += data->basepos-padding;
2056                 spec_btn.rect = rect;
2057                 m_fields.push_back(spec_btn);
2058                 return;
2059         }
2060         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
2061 }
2062
2063 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2064 {
2065         std::vector<std::string> parts = split(element,';');
2066
2067         if ((parts.size() == 3) ||
2068                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2069         {
2070                 std::vector<std::string> v_pos = split(parts[0],',');
2071                 std::vector<std::string> v_geom = split(parts[1],',');
2072
2073                 MY_CHECKPOS("box",0);
2074                 MY_CHECKGEOM("box",1);
2075
2076                 v2s32 pos;
2077                 v2s32 geom;
2078
2079                 if (data->real_coordinates) {
2080                         pos = getRealCoordinateBasePos(v_pos);
2081                         geom = getRealCoordinateGeometry(v_geom);
2082                 } else {
2083                         pos = getElementBasePos(&v_pos);
2084                         geom.X = stof(v_geom[0]) * spacing.X;
2085                         geom.Y = stof(v_geom[1]) * spacing.Y;
2086                 }
2087
2088                 video::SColor tmp_color;
2089
2090                 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2091                         FieldSpec spec(
2092                                 "",
2093                                 L"",
2094                                 L"",
2095                                 258 + m_fields.size(),
2096                                 -2
2097                         );
2098                         spec.ftype = f_Box;
2099
2100                         core::rect<s32> rect(pos, pos + geom);
2101
2102                         GUIBox *e = new GUIBox(Environment, this, spec.fid, rect, tmp_color);
2103
2104                         e->setNotClipped(true);
2105
2106                         e->drop();
2107
2108                         m_fields.push_back(spec);
2109
2110                 } else {
2111                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
2112                 }
2113                 return;
2114         }
2115         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
2116 }
2117
2118 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2119 {
2120         std::vector<std::string> parts = split(element,';');
2121         const u32 parameter_count = parts.size();
2122
2123         if ((parameter_count > 2 && m_formspec_version < 3) ||
2124                         (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2125                 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2126                                 << element << "'" << std::endl;
2127                 return;
2128         }
2129
2130         // bgcolor
2131         if (parameter_count >= 1 && parts[0] != "")
2132                 parseColorString(parts[0], m_bgcolor, false);
2133
2134         // fullscreen
2135         if (parameter_count >= 2) {
2136                 if (parts[1] == "both") {
2137                         m_bgnonfullscreen = true;
2138                         m_bgfullscreen = true;
2139                 } else if (parts[1] == "neither") {
2140                         m_bgnonfullscreen = false;
2141                         m_bgfullscreen = false;
2142                 } else if (parts[1] != "" || m_formspec_version < 3) {
2143                         m_bgfullscreen = is_yes(parts[1]);
2144                         m_bgnonfullscreen = !m_bgfullscreen;
2145                 }
2146         }
2147
2148         // fbgcolor
2149         if (parameter_count >= 3 && parts[2] != "")
2150                 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2151 }
2152
2153 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2154 {
2155         std::vector<std::string> parts = split(element,';');
2156
2157         if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2158                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2159         {
2160                 parseColorString(parts[0], m_slotbg_n, false);
2161                 parseColorString(parts[1], m_slotbg_h, false);
2162
2163                 if (parts.size() >= 3) {
2164                         if (parseColorString(parts[2], m_slotbordercolor, false)) {
2165                                 m_slotborder = true;
2166                         }
2167                 }
2168                 if (parts.size() == 5) {
2169                         video::SColor tmp_color;
2170
2171                         if (parseColorString(parts[3], tmp_color, false))
2172                                 m_default_tooltip_bgcolor = tmp_color;
2173                         if (parseColorString(parts[4], tmp_color, false))
2174                                 m_default_tooltip_color = tmp_color;
2175                 }
2176                 return;
2177         }
2178         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
2179 }
2180
2181 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2182 {
2183         std::vector<std::string> parts = split(element,';');
2184         if (parts.size() < 2) {
2185                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2186                                 << element << "'"  << std::endl;
2187                 return;
2188         }
2189
2190         // Get mode and check size
2191         bool rect_mode = parts[0].find(',') != std::string::npos;
2192         size_t base_size = rect_mode ? 3 : 2;
2193         if (parts.size() != base_size && parts.size() != base_size + 2) {
2194                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2195                                 << element << "'"  << std::endl;
2196                 return;
2197         }
2198
2199         // Read colors
2200         video::SColor bgcolor = m_default_tooltip_bgcolor;
2201         video::SColor color   = m_default_tooltip_color;
2202         if (parts.size() == base_size + 2 &&
2203                         (!parseColorString(parts[base_size], bgcolor, false) ||
2204                                 !parseColorString(parts[base_size + 1], color, false))) {
2205                 errorstream << "Invalid color in tooltip element(" << parts.size()
2206                                 << "): '" << element << "'"  << std::endl;
2207                 return;
2208         }
2209
2210         // Make tooltip spec
2211         std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2212         TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2213
2214         // Add tooltip
2215         if (rect_mode) {
2216                 std::vector<std::string> v_pos  = split(parts[0], ',');
2217                 std::vector<std::string> v_geom = split(parts[1], ',');
2218
2219                 MY_CHECKPOS("tooltip", 0);
2220                 MY_CHECKGEOM("tooltip", 1);
2221
2222                 v2s32 pos;
2223                 v2s32 geom;
2224
2225                 if (data->real_coordinates) {
2226                         pos = getRealCoordinateBasePos(v_pos);
2227                         geom = getRealCoordinateGeometry(v_geom);
2228                 } else {
2229                         pos = getElementBasePos(&v_pos);
2230                         geom.X = stof(v_geom[0]) * spacing.X;
2231                         geom.Y = stof(v_geom[1]) * spacing.Y;
2232                 }
2233
2234                 FieldSpec fieldspec(
2235                         "",
2236                         L"",
2237                         L"",
2238                         258 + m_fields.size()
2239                 );
2240
2241                 core::rect<s32> rect(pos, pos + geom);
2242
2243                 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2244                                 this, fieldspec.fid, rect);
2245
2246                 m_fields.push_back(fieldspec);
2247                 m_tooltip_rects.emplace_back(e, spec);
2248
2249         } else {
2250                 m_tooltips[parts[0]] = spec;
2251         }
2252 }
2253
2254 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2255 {
2256         //some prechecks
2257         if (data.empty())
2258                 return false;
2259
2260         std::vector<std::string> parts = split(data,'[');
2261
2262         if (parts.size() < 2) {
2263                 return false;
2264         }
2265
2266         if (trim(parts[0]) != "formspec_version") {
2267                 return false;
2268         }
2269
2270         if (is_number(parts[1])) {
2271                 m_formspec_version = mystoi(parts[1]);
2272                 return true;
2273         }
2274
2275         return false;
2276 }
2277
2278 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2279 {
2280         if (element.empty())
2281                 return false;
2282
2283         std::vector<std::string> parts = split(element,'[');
2284
2285         if (parts.size() < 2)
2286                 return false;
2287
2288         std::string type = trim(parts[0]);
2289         std::string description = trim(parts[1]);
2290
2291         if (type != "size" && type != "invsize")
2292                 return false;
2293
2294         if (type == "invsize")
2295                 log_deprecated("Deprecated formspec element \"invsize\" is used");
2296
2297         parseSize(data, description);
2298
2299         return true;
2300 }
2301
2302 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2303 {
2304         if (element.empty())
2305                 return false;
2306
2307         std::vector<std::string> parts = split(element, '[');
2308
2309         if (parts.size() != 2)
2310                 return false;
2311
2312         std::string type = trim(parts[0]);
2313         std::string description = trim(parts[1]);
2314
2315         if (type != "position")
2316                 return false;
2317
2318         parsePosition(data, description);
2319
2320         return true;
2321 }
2322
2323 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2324 {
2325         std::vector<std::string> parts = split(element, ',');
2326
2327         if (parts.size() == 2) {
2328                 data->offset.X = stof(parts[0]);
2329                 data->offset.Y = stof(parts[1]);
2330                 return;
2331         }
2332
2333         errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2334 }
2335
2336 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2337 {
2338         if (element.empty())
2339                 return false;
2340
2341         std::vector<std::string> parts = split(element, '[');
2342
2343         if (parts.size() != 2)
2344                 return false;
2345
2346         std::string type = trim(parts[0]);
2347         std::string description = trim(parts[1]);
2348
2349         if (type != "anchor")
2350                 return false;
2351
2352         parseAnchor(data, description);
2353
2354         return true;
2355 }
2356
2357 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2358 {
2359         std::vector<std::string> parts = split(element, ',');
2360
2361         if (parts.size() == 2) {
2362                 data->anchor.X = stof(parts[0]);
2363                 data->anchor.Y = stof(parts[1]);
2364                 return;
2365         }
2366
2367         errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2368                         << "'" << std::endl;
2369 }
2370
2371 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2372 {
2373         std::vector<std::string> parts = split(element, ';');
2374
2375         if (parts.size() < 2) {
2376                 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2377                                         << "'" << std::endl;
2378                 return false;
2379         }
2380
2381         std::string selector = trim(parts[0]);
2382         if (selector.empty()) {
2383                 errorstream << "Invalid style element (Selector required): '" << element
2384                                         << "'" << std::endl;
2385                 return false;
2386         }
2387
2388         StyleSpec spec;
2389
2390         for (size_t i = 1; i < parts.size(); i++) {
2391                 size_t equal_pos = parts[i].find('=');
2392                 if (equal_pos == std::string::npos) {
2393                         errorstream << "Invalid style element (Property missing value): '" << element
2394                                                 << "'" << std::endl;
2395                         return false;
2396                 }
2397
2398                 std::string propname = trim(parts[i].substr(0, equal_pos));
2399                 std::string value    = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2400
2401                 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2402
2403                 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2404                 if (prop == StyleSpec::NONE) {
2405                         if (property_warned.find(propname) != property_warned.end()) {
2406                                 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2407                                                 << element
2408                                                 << "'" << std::endl;
2409                                 property_warned.insert(propname);
2410                         }
2411                         return false;
2412                 }
2413
2414                 spec.set(prop, value);
2415         }
2416
2417         if (style_type) {
2418                 theme_by_type[selector] |= spec;
2419         } else {
2420                 theme_by_name[selector] |= spec;
2421         }
2422
2423         return true;
2424 }
2425
2426 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2427 {
2428         //some prechecks
2429         if (element.empty())
2430                 return;
2431
2432         if (parseVersionDirect(element))
2433                 return;
2434
2435         std::vector<std::string> parts = split(element,'[');
2436
2437         // ugly workaround to keep compatibility
2438         if (parts.size() > 2) {
2439                 if (trim(parts[0]) == "image") {
2440                         for (unsigned int i=2;i< parts.size(); i++) {
2441                                 parts[1] += "[" + parts[i];
2442                         }
2443                 }
2444                 else { return; }
2445         }
2446
2447         if (parts.size() < 2) {
2448                 return;
2449         }
2450
2451         std::string type = trim(parts[0]);
2452         std::string description = trim(parts[1]);
2453
2454         if (type == "container") {
2455                 parseContainer(data, description);
2456                 return;
2457         }
2458
2459         if (type == "container_end") {
2460                 parseContainerEnd(data);
2461                 return;
2462         }
2463
2464         if (type == "list") {
2465                 parseList(data, description);
2466                 return;
2467         }
2468
2469         if (type == "listring") {
2470                 parseListRing(data, description);
2471                 return;
2472         }
2473
2474         if (type == "checkbox") {
2475                 parseCheckbox(data, description);
2476                 return;
2477         }
2478
2479         if (type == "image") {
2480                 parseImage(data, description);
2481                 return;
2482         }
2483
2484         if (type == "item_image") {
2485                 parseItemImage(data, description);
2486                 return;
2487         }
2488
2489         if (type == "button" || type == "button_exit") {
2490                 parseButton(data, description, type);
2491                 return;
2492         }
2493
2494         if (type == "background" || type == "background9") {
2495                 parseBackground(data, description);
2496                 return;
2497         }
2498
2499         if (type == "tableoptions"){
2500                 parseTableOptions(data,description);
2501                 return;
2502         }
2503
2504         if (type == "tablecolumns"){
2505                 parseTableColumns(data,description);
2506                 return;
2507         }
2508
2509         if (type == "table"){
2510                 parseTable(data,description);
2511                 return;
2512         }
2513
2514         if (type == "textlist"){
2515                 parseTextList(data,description);
2516                 return;
2517         }
2518
2519         if (type == "dropdown"){
2520                 parseDropDown(data,description);
2521                 return;
2522         }
2523
2524         if (type == "field_close_on_enter") {
2525                 parseFieldCloseOnEnter(data, description);
2526                 return;
2527         }
2528
2529         if (type == "pwdfield") {
2530                 parsePwdField(data,description);
2531                 return;
2532         }
2533
2534         if ((type == "field") || (type == "textarea")){
2535                 parseField(data,description,type);
2536                 return;
2537         }
2538
2539         if (type == "hypertext") {
2540                 parseHyperText(data,description);
2541                 return;
2542         }
2543
2544         if (type == "label") {
2545                 parseLabel(data,description);
2546                 return;
2547         }
2548
2549         if (type == "vertlabel") {
2550                 parseVertLabel(data,description);
2551                 return;
2552         }
2553
2554         if (type == "item_image_button") {
2555                 parseItemImageButton(data,description);
2556                 return;
2557         }
2558
2559         if ((type == "image_button") || (type == "image_button_exit")) {
2560                 parseImageButton(data,description,type);
2561                 return;
2562         }
2563
2564         if (type == "tabheader") {
2565                 parseTabHeader(data,description);
2566                 return;
2567         }
2568
2569         if (type == "box") {
2570                 parseBox(data,description);
2571                 return;
2572         }
2573
2574         if (type == "bgcolor") {
2575                 parseBackgroundColor(data,description);
2576                 return;
2577         }
2578
2579         if (type == "listcolors") {
2580                 parseListColors(data,description);
2581                 return;
2582         }
2583
2584         if (type == "tooltip") {
2585                 parseTooltip(data,description);
2586                 return;
2587         }
2588
2589         if (type == "scrollbar") {
2590                 parseScrollBar(data, description);
2591                 return;
2592         }
2593
2594         if (type == "real_coordinates") {
2595                 data->real_coordinates = is_yes(description);
2596                 return;
2597         }
2598
2599         if (type == "style") {
2600                 parseStyle(data, description, false);
2601                 return;
2602         }
2603
2604         if (type == "style_type") {
2605                 parseStyle(data, description, true);
2606                 return;
2607         }
2608
2609         if (type == "scrollbaroptions") {
2610                 parseScrollBarOptions(data, description);
2611                 return;
2612         }
2613
2614         // Ignore others
2615         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2616                         << std::endl;
2617 }
2618
2619 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2620 {
2621         /* useless to regenerate without a screensize */
2622         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2623                 return;
2624         }
2625
2626         parserData mydata;
2627
2628         //preserve tables
2629         for (auto &m_table : m_tables) {
2630                 std::string tablename = m_table.first.fname;
2631                 GUITable *table = m_table.second;
2632                 mydata.table_dyndata[tablename] = table->getDynamicData();
2633         }
2634
2635         //set focus
2636         if (!m_focused_element.empty())
2637                 mydata.focused_fieldname = m_focused_element;
2638
2639         //preserve focus
2640         gui::IGUIElement *focused_element = Environment->getFocus();
2641         if (focused_element && focused_element->getParent() == this) {
2642                 s32 focused_id = focused_element->getID();
2643                 if (focused_id > 257) {
2644                         for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2645                                 if (field.fid == focused_id) {
2646                                         mydata.focused_fieldname = field.fname;
2647                                         break;
2648                                 }
2649                         }
2650                 }
2651         }
2652
2653         // Remove children
2654         removeChildren();
2655
2656         for (auto &table_it : m_tables)
2657                 table_it.second->drop();
2658         for (auto &inventorylist_it : m_inventorylists)
2659                 inventorylist_it.e->drop();
2660         for (auto &checkbox_it : m_checkboxes)
2661                 checkbox_it.second->drop();
2662         for (auto &scrollbar_it : m_scrollbars)
2663                 scrollbar_it.second->drop();
2664         for (auto &background_it : m_backgrounds)
2665                 background_it->drop();
2666         for (auto &tooltip_rect_it : m_tooltip_rects)
2667                 tooltip_rect_it.first->drop();
2668
2669         mydata.size= v2s32(100,100);
2670         mydata.screensize = screensize;
2671         mydata.offset = v2f32(0.5f, 0.5f);
2672         mydata.anchor = v2f32(0.5f, 0.5f);
2673         mydata.simple_field_count = 0;
2674
2675         // Base position of contents of form
2676         mydata.basepos = getBasePos();
2677
2678         /* Convert m_init_draw_spec to m_inventorylists */
2679
2680         m_inventorylists.clear();
2681         m_backgrounds.clear();
2682         m_tables.clear();
2683         m_checkboxes.clear();
2684         m_scrollbars.clear();
2685         m_fields.clear();
2686         m_tooltips.clear();
2687         m_tooltip_rects.clear();
2688         m_inventory_rings.clear();
2689         m_dropdowns.clear();
2690         theme_by_name.clear();
2691         theme_by_type.clear();
2692
2693         m_bgnonfullscreen = true;
2694         m_bgfullscreen = false;
2695
2696         m_formspec_version = 1;
2697
2698         {
2699                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2700                 m_bgcolor = video::SColor(
2701                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2702                         clamp_u8(myround(formspec_bgcolor.X)),
2703                         clamp_u8(myround(formspec_bgcolor.Y)),
2704                         clamp_u8(myround(formspec_bgcolor.Z))
2705                 );
2706         }
2707
2708         {
2709                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2710                 m_fullscreen_bgcolor = video::SColor(
2711                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2712                         clamp_u8(myround(formspec_bgcolor.X)),
2713                         clamp_u8(myround(formspec_bgcolor.Y)),
2714                         clamp_u8(myround(formspec_bgcolor.Z))
2715                 );
2716         }
2717
2718         m_slotbg_n = video::SColor(255,128,128,128);
2719         m_slotbg_h = video::SColor(255,192,192,192);
2720
2721         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2722         m_default_tooltip_color = video::SColor(255,255,255,255);
2723
2724         m_slotbordercolor = video::SColor(200,0,0,0);
2725         m_slotborder = false;
2726
2727         // Add tooltip
2728         {
2729                 assert(!m_tooltip_element);
2730                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2731                 m_tooltip_element = gui::StaticText::add(Environment, L"",
2732                         core::rect<s32>(0, 0, 110, 18));
2733                 m_tooltip_element->enableOverrideColor(true);
2734                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2735                 m_tooltip_element->setDrawBackground(true);
2736                 m_tooltip_element->setDrawBorder(true);
2737                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2738                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2739                 m_tooltip_element->setWordWrap(false);
2740                 //we're not parent so no autograb for this one!
2741                 m_tooltip_element->grab();
2742         }
2743
2744         std::vector<std::string> elements = split(m_formspec_string,']');
2745         unsigned int i = 0;
2746
2747         /* try to read version from first element only */
2748         if (!elements.empty()) {
2749                 if (parseVersionDirect(elements[0])) {
2750                         i++;
2751                 }
2752         }
2753
2754         /* we need size first in order to calculate image scale */
2755         mydata.explicit_size = false;
2756         for (; i< elements.size(); i++) {
2757                 if (!parseSizeDirect(&mydata, elements[i])) {
2758                         break;
2759                 }
2760         }
2761
2762         /* "position" element is always after "size" element if it used */
2763         for (; i< elements.size(); i++) {
2764                 if (!parsePositionDirect(&mydata, elements[i])) {
2765                         break;
2766                 }
2767         }
2768
2769         /* "anchor" element is always after "position" (or  "size" element) if it used */
2770         for (; i< elements.size(); i++) {
2771                 if (!parseAnchorDirect(&mydata, elements[i])) {
2772                         break;
2773                 }
2774         }
2775
2776         /* "no_prepend" element is always after "position" (or  "size" element) if it used */
2777         bool enable_prepends = true;
2778         for (; i < elements.size(); i++) {
2779                 if (elements[i].empty())
2780                         break;
2781
2782                 std::vector<std::string> parts = split(elements[i], '[');
2783                 if (trim(parts[0]) == "no_prepend")
2784                         enable_prepends = false;
2785                 else
2786                         break;
2787         }
2788
2789         /* Copy of the "real_coordinates" element for after the form size. */
2790         mydata.real_coordinates = m_formspec_version >= 2;
2791         for (; i < elements.size(); i++) {
2792                 std::vector<std::string> parts = split(elements[i], '[');
2793                 std::string name = trim(parts[0]);
2794                 if (name != "real_coordinates" || parts.size() != 2)
2795                         break; // Invalid format
2796
2797                 mydata.real_coordinates = is_yes(trim(parts[1]));
2798         }
2799
2800         if (mydata.explicit_size) {
2801                 // compute scaling for specified form size
2802                 if (m_lock) {
2803                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2804                         v2u32 delta = current_screensize - m_lockscreensize;
2805
2806                         if (current_screensize.Y > m_lockscreensize.Y)
2807                                 delta.Y /= 2;
2808                         else
2809                                 delta.Y = 0;
2810
2811                         if (current_screensize.X > m_lockscreensize.X)
2812                                 delta.X /= 2;
2813                         else
2814                                 delta.X = 0;
2815
2816                         offset = v2s32(delta.X,delta.Y);
2817
2818                         mydata.screensize = m_lockscreensize;
2819                 } else {
2820                         offset = v2s32(0,0);
2821                 }
2822
2823                 double gui_scaling = g_settings->getFloat("gui_scaling");
2824                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2825
2826                 double use_imgsize;
2827                 if (m_lock) {
2828                         // In fixed-size mode, inventory image size
2829                         // is 0.53 inch multiplied by the gui_scaling
2830                         // config parameter.  This magic size is chosen
2831                         // to make the main menu (15.5 inventory images
2832                         // wide, including border) just fit into the
2833                         // default window (800 pixels wide) at 96 DPI
2834                         // and default scaling (1.00).
2835                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2836                 } else {
2837                         // In variable-size mode, we prefer to make the
2838                         // inventory image size 1/15 of screen height,
2839                         // multiplied by the gui_scaling config parameter.
2840                         // If the preferred size won't fit the whole
2841                         // form on the screen, either horizontally or
2842                         // vertically, then we scale it down to fit.
2843                         // (The magic numbers in the computation of what
2844                         // fits arise from the scaling factors in the
2845                         // following stanza, including the form border,
2846                         // help text space, and 0.1 inventory slot spare.)
2847                         // However, a minimum size is also set, that
2848                         // the image size can't be less than 0.3 inch
2849                         // multiplied by gui_scaling, even if this means
2850                         // the form doesn't fit the screen.
2851 #ifdef __ANDROID__
2852                         // For mobile devices these magic numbers are
2853                         // different and forms should always use the
2854                         // maximum screen space available.
2855                         double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
2856                         double fitx_imgsize = mydata.screensize.X /
2857                                 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
2858                         double fity_imgsize = mydata.screensize.Y /
2859                                 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
2860                         use_imgsize = MYMIN(prefer_imgsize,
2861                                         MYMIN(fitx_imgsize, fity_imgsize));
2862 #else
2863                         double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
2864                         double fitx_imgsize = mydata.screensize.X /
2865                                 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
2866                         double fity_imgsize = mydata.screensize.Y /
2867                                 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
2868                         double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2869                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2870                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2871                                 MYMIN(fitx_imgsize, fity_imgsize)));
2872 #endif
2873                 }
2874
2875                 // Everything else is scaled in proportion to the
2876                 // inventory image size.  The inventory slot spacing
2877                 // is 5/4 image size horizontally and 15/13 image size
2878                 // vertically.  The padding around the form (incorporating
2879                 // the border of the outer inventory slots) is 3/8
2880                 // image size.  Font height (baseline to baseline)
2881                 // is 2/5 vertical inventory slot spacing, and button
2882                 // half-height is 7/8 of font height.
2883                 imgsize = v2s32(use_imgsize, use_imgsize);
2884                 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2885                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2886                 m_btn_height = use_imgsize*15.0/13 * 0.35;
2887
2888                 m_font = g_fontengine->getFont();
2889
2890                 if (mydata.real_coordinates) {
2891                         mydata.size = v2s32(
2892                                 mydata.invsize.X*imgsize.X,
2893                                 mydata.invsize.Y*imgsize.Y
2894                         );
2895                 } else {
2896                         mydata.size = v2s32(
2897                                 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2898                                 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2899                         );
2900                 }
2901
2902                 DesiredRect = mydata.rect = core::rect<s32>(
2903                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2904                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2905                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2906                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2907                 );
2908         } else {
2909                 // Non-size[] form must consist only of text fields and
2910                 // implicit "Proceed" button.  Use default font, and
2911                 // temporary form size which will be recalculated below.
2912                 m_font = g_fontengine->getFont();
2913                 m_btn_height = font_line_height(m_font) * 0.875;
2914                 DesiredRect = core::rect<s32>(
2915                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2916                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2917                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2918                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2919                 );
2920         }
2921         recalculateAbsolutePosition(false);
2922         mydata.basepos = getBasePos();
2923         m_tooltip_element->setOverrideFont(m_font);
2924
2925         gui::IGUISkin *skin = Environment->getSkin();
2926         sanity_check(skin);
2927         gui::IGUIFont *old_font = skin->getFont();
2928         skin->setFont(m_font);
2929
2930         pos_offset = v2f32();
2931
2932         // used for formspec versions < 3
2933         core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
2934
2935         if (enable_prepends) {
2936                 // Backup the coordinates so that prepends can use the coordinates of choice.
2937                 bool rc_backup = mydata.real_coordinates;
2938                 u16 version_backup = m_formspec_version;
2939                 mydata.real_coordinates = false; // Old coordinates by default.
2940
2941                 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
2942                 for (const auto &element : prepend_elements)
2943                         parseElement(&mydata, element);
2944
2945                 // legacy sorting for formspec versions < 3
2946                 if (m_formspec_version >= 3)
2947                         // prepends do not need to be reordered
2948                         legacy_sort_start = Children.getLast();
2949                 else if (version_backup >= 3)
2950                         // only prepends elements have to be reordered
2951                         legacySortElements(legacy_sort_start);
2952
2953                 m_formspec_version = version_backup;
2954                 mydata.real_coordinates = rc_backup; // Restore coordinates
2955         }
2956
2957         for (; i< elements.size(); i++) {
2958                 parseElement(&mydata, elements[i]);
2959         }
2960
2961         if (!container_stack.empty()) {
2962                 errorstream << "Invalid formspec string: container was never closed!"
2963                         << std::endl;
2964         }
2965
2966         // If there are fields without explicit size[], add a "Proceed"
2967         // button and adjust size to fit all the fields.
2968         if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
2969                 mydata.rect = core::rect<s32>(
2970                                 mydata.screensize.X / 2 - 580 / 2,
2971                                 mydata.screensize.Y / 2 - 300 / 2,
2972                                 mydata.screensize.X / 2 + 580 / 2,
2973                                 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
2974                 );
2975
2976                 DesiredRect = mydata.rect;
2977                 recalculateAbsolutePosition(false);
2978                 mydata.basepos = getBasePos();
2979
2980                 {
2981                         v2s32 pos = mydata.basepos;
2982                         pos.Y = (mydata.simple_field_count + 2) * 60;
2983
2984                         v2s32 size = DesiredRect.getSize();
2985                         mydata.rect = core::rect<s32>(
2986                                         size.X / 2 - 70,       pos.Y,
2987                                         size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
2988                         );
2989                         const wchar_t *text = wgettext("Proceed");
2990                         GUIButton::addButton(Environment, mydata.rect, this, 257, text);
2991                         delete[] text;
2992                 }
2993         }
2994
2995         //set initial focus if parser didn't set it
2996         focused_element = Environment->getFocus();
2997         if (!focused_element
2998                         || !isMyChild(focused_element)
2999                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3000                 setInitialFocus();
3001
3002         skin->setFont(old_font);
3003
3004         // legacy sorting
3005         if (m_formspec_version < 3)
3006                 legacySortElements(legacy_sort_start);
3007 }
3008
3009 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3010 {
3011         /*
3012                 Draw order for formspec_version <= 2:
3013                 -3  bgcolor
3014                 -2  background
3015                 -1  box
3016                 0   All other elements
3017                 1   image
3018                 2   item_image, item_image_button
3019                 3   list
3020                 4   label
3021         */
3022
3023         if (from == Children.end())
3024                 from = Children.begin();
3025         else
3026                 from++;
3027
3028         core::list<IGUIElement *>::Iterator to = Children.end();
3029         // 1: Copy into a sortable container
3030         std::vector<IGUIElement *> elements;
3031         for (auto it = from; it != to; ++it)
3032                 elements.emplace_back(*it);
3033
3034         // 2: Sort the container
3035         std::stable_sort(elements.begin(), elements.end(),
3036                         [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3037                 const FieldSpec *spec_a = getSpecByID(a->getID());
3038                 const FieldSpec *spec_b = getSpecByID(b->getID());
3039                 return spec_a && spec_b &&
3040                         spec_a->priority < spec_b->priority;
3041         });
3042
3043         // 3: Re-assign the pointers
3044         for (auto e : elements) {
3045                 *from = e;
3046                 from++;
3047         }
3048 }
3049
3050 #ifdef __ANDROID__
3051 bool GUIFormSpecMenu::getAndroidUIInput()
3052 {
3053         if (!hasAndroidUIInput())
3054                 return false;
3055
3056         std::string fieldname = m_jni_field_name;
3057         m_jni_field_name.clear();
3058
3059         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3060                         iter != m_fields.end(); ++iter) {
3061
3062                 if (iter->fname != fieldname) {
3063                         continue;
3064                 }
3065                 IGUIElement *tochange = getElementFromId(iter->fid, true);
3066
3067                 if (tochange == 0) {
3068                         return false;
3069                 }
3070
3071                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
3072                         return false;
3073                 }
3074
3075                 std::string text = porting::getInputDialogValue();
3076
3077                 ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
3078         }
3079         return false;
3080 }
3081 #endif
3082
3083 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3084 {
3085         core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3086
3087         for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3088                 core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3089                 v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3090                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
3091                         s32 item_i = i + s.start_item_i;
3092
3093                         s32 x;
3094                         s32 y;
3095                         if (s.real_coordinates) {
3096                                 x = (i%s.geom.X) * (imgsize.X * 1.25);
3097                                 y = (i/s.geom.X) * (imgsize.Y * 1.25);
3098                         } else {
3099                                 x = (i%s.geom.X) * spacing.X;
3100                                 y = (i/s.geom.X) * spacing.Y;
3101                         }
3102                         v2s32 p0(x,y);
3103                         core::rect<s32> rect = imgrect + base_pos + p0;
3104                         rect.clipAgainst(clipping_rect);
3105                         if (rect.getArea() > 0 && rect.isPointInside(p))
3106                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
3107                 }
3108         }
3109
3110         return ItemSpec(InventoryLocation(), "", -1);
3111 }
3112
3113 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer,
3114                 bool &item_hovered)
3115 {
3116         video::IVideoDriver* driver = Environment->getVideoDriver();
3117
3118         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3119         if (!inv) {
3120                 warningstream<<"GUIFormSpecMenu::drawList(): "
3121                                 << "The inventory location "
3122                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist anymore"
3123                                 << std::endl;
3124                 return;
3125         }
3126         InventoryList *ilist = inv->getList(s.listname);
3127         if (!ilist) {
3128                 warningstream << "GUIFormSpecMenu::drawList(): "
3129                                 << "The inventory list \"" << s.listname << "\" @ \""
3130                                 << s.inventoryloc.dump() << "\" doesn't exist anymore"
3131                                 << std::endl;
3132                 return;
3133         }
3134
3135         core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3136         core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3137         v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3138
3139         for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) {
3140                 s32 item_i = i + s.start_item_i;
3141                 if (item_i >= (s32)ilist->getSize())
3142                         break;
3143
3144                 s32 x;
3145                 s32 y;
3146                 if (s.real_coordinates) {
3147                         x = (i%s.geom.X) * (imgsize.X * 1.25);
3148                         y = (i/s.geom.X) * (imgsize.Y * 1.25);
3149                 } else {
3150                         x = (i%s.geom.X) * spacing.X;
3151                         y = (i/s.geom.X) * spacing.Y;
3152                 }
3153                 v2s32 p(x,y);
3154                 core::rect<s32> rect = imgrect + base_pos + p;
3155                 ItemStack item = ilist->getItem(item_i);
3156
3157                 bool selected = m_selected_item
3158                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
3159                         && m_selected_item->listname == s.listname
3160                         && m_selected_item->i == item_i;
3161                 core::rect<s32> clipped_rect(rect);
3162                 clipped_rect.clipAgainst(clipping_rect);
3163                 bool hovering = clipped_rect.getArea() > 0 &&
3164                                 clipped_rect.isPointInside(m_pointer);
3165                 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
3166                         (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
3167
3168                 if (layer == 0) {
3169                         if (hovering) {
3170                                 item_hovered = true;
3171                                 driver->draw2DRectangle(m_slotbg_h, rect, &clipping_rect);
3172                         } else {
3173                                 driver->draw2DRectangle(m_slotbg_n, rect, &clipping_rect);
3174                         }
3175                 }
3176
3177                 //Draw inv slot borders
3178                 if (m_slotborder) {
3179                         s32 x1 = rect.UpperLeftCorner.X;
3180                         s32 y1 = rect.UpperLeftCorner.Y;
3181                         s32 x2 = rect.LowerRightCorner.X;
3182                         s32 y2 = rect.LowerRightCorner.Y;
3183                         s32 border = 1;
3184                         driver->draw2DRectangle(m_slotbordercolor,
3185                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
3186                                                                 v2s32(x2 + border, y1)), &clipping_rect);
3187                         driver->draw2DRectangle(m_slotbordercolor,
3188                                 core::rect<s32>(v2s32(x1 - border, y2),
3189                                                                 v2s32(x2 + border, y2 + border)), &clipping_rect);
3190                         driver->draw2DRectangle(m_slotbordercolor,
3191                                 core::rect<s32>(v2s32(x1 - border, y1),
3192                                                                 v2s32(x1, y2)), &clipping_rect);
3193                         driver->draw2DRectangle(m_slotbordercolor,
3194                                 core::rect<s32>(v2s32(x2, y1),
3195                                                                 v2s32(x2 + border, y2)), &clipping_rect);
3196                 }
3197
3198                 if (layer == 1) {
3199                         if (selected)
3200                                 item.takeItem(m_selected_amount);
3201
3202                         if (!item.empty()) {
3203                                 // Draw item stack
3204                                 drawItemStack(driver, m_font, item,
3205                                         rect, &clipping_rect, m_client, rotation_kind);
3206                                 // Draw tooltip
3207                                 if (hovering && !m_selected_item) {
3208                                         std::string tooltip = item.getDescription(m_client->idef());
3209                                         if (m_tooltip_append_itemname)
3210                                                 tooltip += "\n[" + item.name + "]";
3211                                         showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3212                                                         m_default_tooltip_bgcolor);
3213                                 }
3214                         }
3215                 }
3216         }
3217 }
3218
3219 void GUIFormSpecMenu::drawSelectedItem()
3220 {
3221         video::IVideoDriver* driver = Environment->getVideoDriver();
3222
3223         if (!m_selected_item) {
3224                 // reset rotation time
3225                 drawItemStack(driver, m_font, ItemStack(),
3226                                 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3227                                 m_client, IT_ROT_DRAGGED);
3228                 return;
3229         }
3230
3231         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3232         sanity_check(inv);
3233         InventoryList *list = inv->getList(m_selected_item->listname);
3234         sanity_check(list);
3235         ItemStack stack = list->getItem(m_selected_item->i);
3236         stack.count = m_selected_amount;
3237
3238         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3239         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3240         rect.constrainTo(driver->getViewPort());
3241         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3242 }
3243
3244 void GUIFormSpecMenu::drawMenu()
3245 {
3246         if (m_form_src) {
3247                 const std::string &newform = m_form_src->getForm();
3248                 if (newform != m_formspec_string) {
3249                         m_formspec_string = newform;
3250                         regenerateGui(m_screensize_old);
3251                 }
3252         }
3253
3254         gui::IGUISkin* skin = Environment->getSkin();
3255         sanity_check(skin != NULL);
3256         gui::IGUIFont *old_font = skin->getFont();
3257         skin->setFont(m_font);
3258
3259         updateSelectedItem();
3260
3261         video::IVideoDriver* driver = Environment->getVideoDriver();
3262
3263         /*
3264                 Draw background color
3265         */
3266         v2u32 screenSize = driver->getScreenSize();
3267         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3268
3269         if (m_bgfullscreen)
3270                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3271         if (m_bgnonfullscreen)
3272                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3273
3274         /*
3275                 Draw rect_mode tooltip
3276         */
3277         m_tooltip_element->setVisible(false);
3278
3279         for (const auto &pair : m_tooltip_rects) {
3280                 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3281                 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3282                         const std::wstring &text = pair.second.tooltip;
3283                         if (!text.empty()) {
3284                                 showTooltip(text, pair.second.color, pair.second.bgcolor);
3285                                 break;
3286                         }
3287                 }
3288         }
3289
3290         /*
3291                 Draw backgrounds
3292         */
3293         for (gui::IGUIElement *e : m_backgrounds) {
3294                 e->setVisible(true);
3295                 e->draw();
3296                 e->setVisible(false);
3297         }
3298
3299         /*
3300                 Call base class
3301         */
3302         gui::IGUIElement::draw();
3303
3304         /*
3305                 Draw items
3306                 Layer 0: Item slot rectangles
3307                 Layer 1: Item images; prepare tooltip
3308         */
3309         bool item_hovered = false;
3310         for (int layer = 0; layer < 2; layer++) {
3311                 for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
3312                         drawList(spec, layer, item_hovered);
3313                 }
3314         }
3315         if (!item_hovered) {
3316                 // reset rotation time
3317                 drawItemStack(driver, m_font, ItemStack(),
3318                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3319                         NULL, m_client, IT_ROT_HOVERED);
3320         }
3321
3322 /* TODO find way to show tooltips on touchscreen */
3323 #ifndef HAVE_TOUCHSCREENGUI
3324         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3325 #endif
3326
3327         /*
3328                 Draw fields/buttons tooltips
3329         */
3330         gui::IGUIElement *hovered =
3331                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3332
3333         if (hovered != NULL) {
3334                 s32 id = hovered->getID();
3335
3336                 u64 delta = 0;
3337                 if (id == -1) {
3338                         m_old_tooltip_id = id;
3339                 } else {
3340                         if (id == m_old_tooltip_id) {
3341                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3342                         } else {
3343                                 m_hovered_time = porting::getTimeMs();
3344                                 m_old_tooltip_id = id;
3345                         }
3346                 }
3347
3348                 // Find and update the current tooltip
3349                 if (id != -1 && delta >= m_tooltip_show_delay) {
3350                         for (const FieldSpec &field : m_fields) {
3351
3352                                 if (field.fid != id)
3353                                         continue;
3354
3355                                 const std::wstring &text = m_tooltips[field.fname].tooltip;
3356                                 if (!text.empty())
3357                                         showTooltip(text, m_tooltips[field.fname].color,
3358                                                 m_tooltips[field.fname].bgcolor);
3359
3360                                 break;
3361                         }
3362                 }
3363         }
3364
3365         m_tooltip_element->draw();
3366
3367         /*
3368                 Draw dragged item stack
3369         */
3370         drawSelectedItem();
3371
3372         skin->setFont(old_font);
3373 }
3374
3375
3376 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3377         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3378 {
3379         const std::wstring ntext = translate_string(text);
3380         m_tooltip_element->setOverrideColor(color);
3381         m_tooltip_element->setBackgroundColor(bgcolor);
3382         setStaticText(m_tooltip_element, ntext.c_str());
3383
3384         // Tooltip size and offset
3385         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3386 #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
3387         std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
3388         s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
3389 #else
3390         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3391 #endif
3392         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3393         int tooltip_offset_x = m_btn_height;
3394         int tooltip_offset_y = m_btn_height;
3395 #ifdef __ANDROID__
3396         tooltip_offset_x *= 3;
3397         tooltip_offset_y  = 0;
3398         if (m_pointer.X > (s32)screenSize.X / 2)
3399                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3400 #endif
3401
3402         // Calculate and set the tooltip position
3403         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3404         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3405         if (tooltip_x + tooltip_width > (s32)screenSize.X)
3406                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
3407         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3408                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3409
3410         m_tooltip_element->setRelativePosition(
3411                 core::rect<s32>(
3412                         core::position2d<s32>(tooltip_x, tooltip_y),
3413                         core::dimension2d<s32>(tooltip_width, tooltip_height)
3414                 )
3415         );
3416
3417         // Display the tooltip
3418         m_tooltip_element->setVisible(true);
3419         bringToFront(m_tooltip_element);
3420 }
3421
3422 void GUIFormSpecMenu::updateSelectedItem()
3423 {
3424         verifySelectedItem();
3425
3426         // If craftresult is nonempty and nothing else is selected, select it now.
3427         if (!m_selected_item) {
3428                 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3429                         if (s.listname != "craftpreview")
3430                                 continue;
3431
3432                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3433                         if (!inv)
3434                                 continue;
3435
3436                         InventoryList *list = inv->getList("craftresult");
3437
3438                         if (!list || list->getSize() == 0)
3439                                 continue;
3440
3441                         const ItemStack &item = list->getItem(0);
3442                         if (item.empty())
3443                                 continue;
3444
3445                         // Grab selected item from the crafting result list
3446                         m_selected_item = new ItemSpec;
3447                         m_selected_item->inventoryloc = s.inventoryloc;
3448                         m_selected_item->listname = "craftresult";
3449                         m_selected_item->i = 0;
3450                         m_selected_amount = item.count;
3451                         m_selected_dragging = false;
3452                         break;
3453                 }
3454         }
3455
3456         // If craftresult is selected, keep the whole stack selected
3457         if (m_selected_item && m_selected_item->listname == "craftresult")
3458                 m_selected_amount = verifySelectedItem().count;
3459 }
3460
3461 ItemStack GUIFormSpecMenu::verifySelectedItem()
3462 {
3463         // If the selected stack has become empty for some reason, deselect it.
3464         // If the selected stack has become inaccessible, deselect it.
3465         // If the selected stack has become smaller, adjust m_selected_amount.
3466         // Return the selected stack.
3467
3468         if(m_selected_item)
3469         {
3470                 if(m_selected_item->isValid())
3471                 {
3472                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3473                         if(inv)
3474                         {
3475                                 InventoryList *list = inv->getList(m_selected_item->listname);
3476                                 if(list && (u32) m_selected_item->i < list->getSize())
3477                                 {
3478                                         ItemStack stack = list->getItem(m_selected_item->i);
3479                                         if (!m_selected_swap.empty()) {
3480                                                 if (m_selected_swap.name == stack.name &&
3481                                                                 m_selected_swap.count == stack.count)
3482                                                         m_selected_swap.clear();
3483                                         } else {
3484                                                 m_selected_amount = std::min(m_selected_amount, stack.count);
3485                                         }
3486
3487                                         if (!stack.empty())
3488                                                 return stack;
3489                                 }
3490                         }
3491                 }
3492
3493                 // selection was not valid
3494                 delete m_selected_item;
3495                 m_selected_item = NULL;
3496                 m_selected_amount = 0;
3497                 m_selected_dragging = false;
3498         }
3499         return ItemStack();
3500 }
3501
3502 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3503 {
3504         if(m_text_dst)
3505         {
3506                 StringMap fields;
3507
3508                 if (quitmode == quit_mode_accept) {
3509                         fields["quit"] = "true";
3510                 }
3511
3512                 if (quitmode == quit_mode_cancel) {
3513                         fields["quit"] = "true";
3514                         m_text_dst->gotText(fields);
3515                         return;
3516                 }
3517
3518                 if (current_keys_pending.key_down) {
3519                         fields["key_down"] = "true";
3520                         current_keys_pending.key_down = false;
3521                 }
3522
3523                 if (current_keys_pending.key_up) {
3524                         fields["key_up"] = "true";
3525                         current_keys_pending.key_up = false;
3526                 }
3527
3528                 if (current_keys_pending.key_enter) {
3529                         fields["key_enter"] = "true";
3530                         current_keys_pending.key_enter = false;
3531                 }
3532
3533                 if (!current_field_enter_pending.empty()) {
3534                         fields["key_enter_field"] = current_field_enter_pending;
3535                         current_field_enter_pending = "";
3536                 }
3537
3538                 if (current_keys_pending.key_escape) {
3539                         fields["key_escape"] = "true";
3540                         current_keys_pending.key_escape = false;
3541                 }
3542
3543                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3544                         if(s.send) {
3545                                 std::string name = s.fname;
3546                                 if (s.ftype == f_Button) {
3547                                         fields[name] = wide_to_utf8(s.flabel);
3548                                 } else if (s.ftype == f_Table) {
3549                                         GUITable *table = getTable(s.fname);
3550                                         if (table) {
3551                                                 fields[name] = table->checkEvent();
3552                                         }
3553                                 }
3554                                 else if(s.ftype == f_DropDown) {
3555                                         // no dynamic cast possible due to some distributions shipped
3556                                         // without rtti support in irrlicht
3557                                         IGUIElement *element = getElementFromId(s.fid, true);
3558                                         gui::IGUIComboBox *e = NULL;
3559                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3560                                                 e = static_cast<gui::IGUIComboBox*>(element);
3561                                         } else {
3562                                                 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3563                                                                 << "field without dropdown element" << std::endl;
3564                                                 continue;
3565                                         }
3566                                         s32 selected = e->getSelected();
3567                                         if (selected >= 0) {
3568                                                 std::vector<std::string> *dropdown_values =
3569                                                         getDropDownValues(s.fname);
3570                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3571                                                         fields[name] = (*dropdown_values)[selected];
3572                                                 }
3573                                         }
3574                                 }
3575                                 else if (s.ftype == f_TabHeader) {
3576                                         // no dynamic cast possible due to some distributions shipped
3577                                         // without rttzi support in irrlicht
3578                                         IGUIElement *element = getElementFromId(s.fid, true);
3579                                         gui::IGUITabControl *e = nullptr;
3580                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3581                                                 e = static_cast<gui::IGUITabControl *>(element);
3582                                         }
3583
3584                                         if (e != 0) {
3585                                                 std::stringstream ss;
3586                                                 ss << (e->getActiveTab() +1);
3587                                                 fields[name] = ss.str();
3588                                         }
3589                                 }
3590                                 else if (s.ftype == f_CheckBox) {
3591                                         // no dynamic cast possible due to some distributions shipped
3592                                         // without rtti support in irrlicht
3593                                         IGUIElement *element = getElementFromId(s.fid, true);
3594                                         gui::IGUICheckBox *e = nullptr;
3595                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3596                                                 e = static_cast<gui::IGUICheckBox*>(element);
3597                                         }
3598
3599                                         if (e != 0) {
3600                                                 if (e->isChecked())
3601                                                         fields[name] = "true";
3602                                                 else
3603                                                         fields[name] = "false";
3604                                         }
3605                                 }
3606                                 else if (s.ftype == f_ScrollBar) {
3607                                         // no dynamic cast possible due to some distributions shipped
3608                                         // without rtti support in irrlicht
3609                                         IGUIElement *element = getElementFromId(s.fid, true);
3610                                         GUIScrollBar *e = nullptr;
3611                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3612                                                 e = static_cast<GUIScrollBar *>(element);
3613
3614                                         if (e) {
3615                                                 std::stringstream os;
3616                                                 os << e->getPos();
3617                                                 if (s.fdefault == L"Changed")
3618                                                         fields[name] = "CHG:" + os.str();
3619                                                 else
3620                                                         fields[name] = "VAL:" + os.str();
3621                                         }
3622                                 }
3623                                 else {
3624                                         IGUIElement *e = getElementFromId(s.fid, true);
3625                                         if (e)
3626                                                 fields[name] = wide_to_utf8(e->getText());
3627                                 }
3628                         }
3629                 }
3630
3631                 m_text_dst->gotText(fields);
3632         }
3633 }
3634
3635 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
3636 {
3637         while(tocheck != NULL) {
3638                 if (tocheck == parent) {
3639                         return true;
3640                 }
3641                 tocheck = tocheck->getParent();
3642         }
3643         return false;
3644 }
3645
3646 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3647 {
3648         // The IGUITabControl renders visually using the skin's selected
3649         // font, which we override for the duration of form drawing,
3650         // but computes tab hotspots based on how it would have rendered
3651         // using the font that is selected at the time of button release.
3652         // To make these two consistent, temporarily override the skin's
3653         // font while the IGUITabControl is processing the event.
3654         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3655                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3656                 s32 x = event.MouseInput.X;
3657                 s32 y = event.MouseInput.Y;
3658                 gui::IGUIElement *hovered =
3659                         Environment->getRootGUIElement()->getElementFromPoint(
3660                                 core::position2d<s32>(x, y));
3661                 if (hovered && isMyChild(hovered) &&
3662                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3663                         gui::IGUISkin* skin = Environment->getSkin();
3664                         sanity_check(skin != NULL);
3665                         gui::IGUIFont *old_font = skin->getFont();
3666                         skin->setFont(m_font);
3667                         bool retval = hovered->OnEvent(event);
3668                         skin->setFont(old_font);
3669                         return retval;
3670                 }
3671         }
3672
3673         // Fix Esc/Return key being eaten by checkboxen and tables
3674         if(event.EventType==EET_KEY_INPUT_EVENT) {
3675                 KeyPress kp(event.KeyInput);
3676                 if (kp == EscapeKey || kp == CancelKey
3677                                 || kp == getKeySetting("keymap_inventory")
3678                                 || event.KeyInput.Key==KEY_RETURN) {
3679                         gui::IGUIElement *focused = Environment->getFocus();
3680                         if (focused && isMyChild(focused) &&
3681                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
3682                                         focused->getType() == gui::EGUIET_CHECK_BOX) &&
3683                                         (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3684                                         event.KeyInput.Key != KEY_RETURN)) {
3685                                 OnEvent(event);
3686                                 return true;
3687                         }
3688                 }
3689         }
3690         // Mouse wheel and move events: send to hovered element instead of focused
3691         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3692                         (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3693                          event.MouseInput.Event == EMIE_MOUSE_MOVED)) {
3694                 s32 x = event.MouseInput.X;
3695                 s32 y = event.MouseInput.Y;
3696                 gui::IGUIElement *hovered =
3697                         Environment->getRootGUIElement()->getElementFromPoint(
3698                                 core::position2d<s32>(x, y));
3699                 if (hovered && isMyChild(hovered)) {
3700                         hovered->OnEvent(event);
3701                         return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3702                 }
3703         }
3704
3705         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3706                 s32 x = event.MouseInput.X;
3707                 s32 y = event.MouseInput.Y;
3708                 gui::IGUIElement *hovered =
3709                         Environment->getRootGUIElement()->getElementFromPoint(
3710                                 core::position2d<s32>(x, y));
3711                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3712                         m_old_tooltip_id = -1;
3713                 }
3714                 if (!isChild(hovered,this)) {
3715                         if (DoubleClickDetection(event)) {
3716                                 return true;
3717                         }
3718                 }
3719         }
3720
3721         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3722                 /* TODO add a check like:
3723                 if (event.JoystickEvent != joystick_we_listen_for)
3724                         return false;
3725                 */
3726                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3727                 if (handled) {
3728                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
3729                                 tryClose();
3730                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3731                                 if (m_allowclose) {
3732                                         acceptInput(quit_mode_accept);
3733                                         quitMenu();
3734                                 }
3735                         }
3736                 }
3737                 return handled;
3738         }
3739
3740         return GUIModalMenu::preprocessEvent(event);
3741 }
3742
3743 /******************************************************************************/
3744 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3745 {
3746         /* The following code is for capturing double-clicks of the mouse button
3747          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3748          * -- which closes the form -- under some circumstances.
3749          *
3750          * There have been many github issues reporting this as a bug even though it
3751          * was an intended feature.  For this reason, remapping the double-click as
3752          * an ESC must be explicitly set when creating this class via the
3753          * /p remap_dbl_click parameter of the constructor.
3754          */
3755
3756         if (!m_remap_dbl_click)
3757                 return false;
3758
3759         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3760                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3761                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3762
3763                 m_doubleclickdetect[1].pos  = m_pointer;
3764                 m_doubleclickdetect[1].time = porting::getTimeMs();
3765         }
3766         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3767                 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3768                 if (delta > 400) {
3769                         return false;
3770                 }
3771
3772                 double squaredistance =
3773                                 m_doubleclickdetect[0].pos
3774                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3775
3776                 if (squaredistance > (30*30)) {
3777                         return false;
3778                 }
3779
3780                 SEvent* translated = new SEvent();
3781                 assert(translated != 0);
3782                 //translate doubleclick to escape
3783                 memset(translated, 0, sizeof(SEvent));
3784                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3785                 translated->KeyInput.Key         = KEY_ESCAPE;
3786                 translated->KeyInput.Control     = false;
3787                 translated->KeyInput.Shift       = false;
3788                 translated->KeyInput.PressedDown = true;
3789                 translated->KeyInput.Char        = 0;
3790                 OnEvent(*translated);
3791
3792                 // no need to send the key up event as we're already deleted
3793                 // and no one else did notice this event
3794                 delete translated;
3795                 return true;
3796         }
3797
3798         return false;
3799 }
3800
3801 void GUIFormSpecMenu::tryClose()
3802 {
3803         if (m_allowclose) {
3804                 doPause = false;
3805                 acceptInput(quit_mode_cancel);
3806                 quitMenu();
3807         } else {
3808                 m_text_dst->gotText(L"MenuQuit");
3809         }
3810 }
3811
3812 enum ButtonEventType : u8
3813 {
3814         BET_LEFT,
3815         BET_RIGHT,
3816         BET_MIDDLE,
3817         BET_WHEEL_UP,
3818         BET_WHEEL_DOWN,
3819         BET_UP,
3820         BET_DOWN,
3821         BET_MOVE,
3822         BET_OTHER
3823 };
3824
3825 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3826 {
3827         if (event.EventType==EET_KEY_INPUT_EVENT) {
3828                 KeyPress kp(event.KeyInput);
3829                 if (event.KeyInput.PressedDown && (
3830                                 (kp == EscapeKey) || (kp == CancelKey) ||
3831                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3832                         tryClose();
3833                         return true;
3834                 }
3835
3836                 if (m_client != NULL && event.KeyInput.PressedDown &&
3837                                 (kp == getKeySetting("keymap_screenshot"))) {
3838                         m_client->makeScreenshot();
3839                 }
3840                 if (event.KeyInput.PressedDown &&
3841                         (event.KeyInput.Key==KEY_RETURN ||
3842                          event.KeyInput.Key==KEY_UP ||
3843                          event.KeyInput.Key==KEY_DOWN)
3844                         ) {
3845                         switch (event.KeyInput.Key) {
3846                                 case KEY_RETURN:
3847                                         current_keys_pending.key_enter = true;
3848                                         break;
3849                                 case KEY_UP:
3850                                         current_keys_pending.key_up = true;
3851                                         break;
3852                                 case KEY_DOWN:
3853                                         current_keys_pending.key_down = true;
3854                                         break;
3855                                 break;
3856                                 default:
3857                                         //can't happen at all!
3858                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3859                                         break;
3860                         }
3861                         if (current_keys_pending.key_enter && m_allowclose) {
3862                                 acceptInput(quit_mode_accept);
3863                                 quitMenu();
3864                         } else {
3865                                 acceptInput();
3866                         }
3867                         return true;
3868                 }
3869
3870         }
3871
3872         /* Mouse event other than movement, or crossing the border of inventory
3873           field while holding right mouse button
3874          */
3875         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3876                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3877                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3878                           event.MouseInput.isRightPressed() &&
3879                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3880
3881                 // Get selected item and hovered/clicked item (s)
3882
3883                 m_old_tooltip_id = -1;
3884                 updateSelectedItem();
3885                 ItemSpec s = getItemAtPos(m_pointer);
3886
3887                 Inventory *inv_selected = NULL;
3888                 Inventory *inv_s = NULL;
3889                 InventoryList *list_s = NULL;
3890
3891                 if (m_selected_item) {
3892                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3893                         sanity_check(inv_selected);
3894                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3895                 }
3896
3897                 u32 s_count = 0;
3898
3899                 if (s.isValid())
3900                 do { // breakable
3901                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3902
3903                         if (!inv_s) {
3904                                 errorstream << "InventoryMenu: The selected inventory location "
3905                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3906                                                 << std::endl;
3907                                 s.i = -1;  // make it invalid again
3908                                 break;
3909                         }
3910
3911                         list_s = inv_s->getList(s.listname);
3912                         if (list_s == NULL) {
3913                                 verbosestream << "InventoryMenu: The selected inventory list \""
3914                                                 << s.listname << "\" does not exist" << std::endl;
3915                                 s.i = -1;  // make it invalid again
3916                                 break;
3917                         }
3918
3919                         if ((u32)s.i >= list_s->getSize()) {
3920                                 infostream << "InventoryMenu: The selected inventory list \""
3921                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
3922                                                 << list_s->getSize() << ")" << std::endl;
3923                                 s.i = -1;  // make it invalid again
3924                                 break;
3925                         }
3926
3927                         s_count = list_s->getItem(s.i).count;
3928                 } while(0);
3929
3930                 bool identical = m_selected_item && s.isValid() &&
3931                         (inv_selected == inv_s) &&
3932                         (m_selected_item->listname == s.listname) &&
3933                         (m_selected_item->i == s.i);
3934
3935                 ButtonEventType button = BET_LEFT;
3936                 ButtonEventType updown = BET_OTHER;
3937                 switch (event.MouseInput.Event) {
3938                 case EMIE_LMOUSE_PRESSED_DOWN:
3939                         button = BET_LEFT; updown = BET_DOWN;
3940                         break;
3941                 case EMIE_RMOUSE_PRESSED_DOWN:
3942                         button = BET_RIGHT; updown = BET_DOWN;
3943                         break;
3944                 case EMIE_MMOUSE_PRESSED_DOWN:
3945                         button = BET_MIDDLE; updown = BET_DOWN;
3946                         break;
3947                 case EMIE_MOUSE_WHEEL:
3948                         button = (event.MouseInput.Wheel > 0) ?
3949                                 BET_WHEEL_UP : BET_WHEEL_DOWN;
3950                         updown = BET_DOWN;
3951                         break;
3952                 case EMIE_LMOUSE_LEFT_UP:
3953                         button = BET_LEFT; updown = BET_UP;
3954                         break;
3955                 case EMIE_RMOUSE_LEFT_UP:
3956                         button = BET_RIGHT; updown = BET_UP;
3957                         break;
3958                 case EMIE_MMOUSE_LEFT_UP:
3959                         button = BET_MIDDLE; updown = BET_UP;
3960                         break;
3961                 case EMIE_MOUSE_MOVED:
3962                         updown = BET_MOVE;
3963                         break;
3964                 default:
3965                         break;
3966                 }
3967
3968                 // Set this number to a positive value to generate a move action
3969                 // from m_selected_item to s.
3970                 u32 move_amount = 0;
3971
3972                 // Set this number to a positive value to generate a move action
3973                 // from s to the next inventory ring.
3974                 u32 shift_move_amount = 0;
3975
3976                 // Set this number to a positive value to generate a drop action
3977                 // from m_selected_item.
3978                 u32 drop_amount = 0;
3979
3980                 // Set this number to a positive value to generate a craft action at s.
3981                 u32 craft_amount = 0;
3982
3983                 switch (updown) {
3984                 case BET_DOWN:
3985                         // Some mouse button has been pressed
3986
3987                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3988                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3989
3990                         m_selected_dragging = false;
3991
3992                         if (s.isValid() && s.listname == "craftpreview") {
3993                                 // Craft preview has been clicked: craft
3994                                 craft_amount = (button == BET_MIDDLE ? 10 : 1);
3995                         } else if (!m_selected_item) {
3996                                 if (s_count && button != BET_WHEEL_UP) {
3997                                         // Non-empty stack has been clicked: select or shift-move it
3998                                         m_selected_item = new ItemSpec(s);
3999
4000                                         u32 count;
4001                                         if (button == BET_RIGHT)
4002                                                 count = (s_count + 1) / 2;
4003                                         else if (button == BET_MIDDLE)
4004                                                 count = MYMIN(s_count, 10);
4005                                         else if (button == BET_WHEEL_DOWN)
4006                                                 count = 1;
4007                                         else  // left
4008                                                 count = s_count;
4009
4010                                         if (!event.MouseInput.Shift) {
4011                                                 // no shift: select item
4012                                                 m_selected_amount = count;
4013                                                 m_selected_dragging = button != BET_WHEEL_DOWN;
4014                                                 m_auto_place = false;
4015                                         } else {
4016                                                 // shift pressed: move item, right click moves 1
4017                                                 shift_move_amount = button == BET_RIGHT ? 1 : count;
4018                                         }
4019                                 }
4020                         } else { // m_selected_item != NULL
4021                                 assert(m_selected_amount >= 1);
4022
4023                                 if (s.isValid()) {
4024                                         // Clicked a slot: move
4025                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4026                                                 move_amount = 1;
4027                                         else if (button == BET_MIDDLE)
4028                                                 move_amount = MYMIN(m_selected_amount, 10);
4029                                         else if (button == BET_LEFT)
4030                                                 move_amount = m_selected_amount;
4031                                         // else wheeldown
4032
4033                                         if (identical) {
4034                                                 if (button == BET_WHEEL_DOWN) {
4035                                                         if (m_selected_amount < s_count)
4036                                                                 ++m_selected_amount;
4037                                                 } else {
4038                                                         if (move_amount >= m_selected_amount)
4039                                                                 m_selected_amount = 0;
4040                                                         else
4041                                                                 m_selected_amount -= move_amount;
4042                                                         move_amount = 0;
4043                                                 }
4044                                         }
4045                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4046                                                 && button != BET_WHEEL_DOWN) {
4047                                         // Clicked outside of the window: drop
4048                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4049                                                 drop_amount = 1;
4050                                         else if (button == BET_MIDDLE)
4051                                                 drop_amount = MYMIN(m_selected_amount, 10);
4052                                         else  // left
4053                                                 drop_amount = m_selected_amount;
4054                                 }
4055                         }
4056                 break;
4057                 case BET_UP:
4058                         // Some mouse button has been released
4059
4060                         //infostream<<"Mouse button "<<button<<" released at p=("
4061                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
4062
4063                         if (m_selected_dragging && m_selected_item) {
4064                                 if (s.isValid()) {
4065                                         if (!identical) {
4066                                                 // Dragged to different slot: move all selected
4067                                                 move_amount = m_selected_amount;
4068                                         }
4069                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4070                                         // Dragged outside of window: drop all selected
4071                                         drop_amount = m_selected_amount;
4072                                 }
4073                         }
4074
4075                         m_selected_dragging = false;
4076                         // Keep track of whether the mouse button be released
4077                         // One click is drag without dropping. Click + release
4078                         // + click changes to drop item when moved mode
4079                         if (m_selected_item)
4080                                 m_auto_place = true;
4081                 break;
4082                 case BET_MOVE:
4083                         // Mouse has been moved and rmb is down and mouse pointer just
4084                         // entered a new inventory field (checked in the entry-if, this
4085                         // is the only action here that is generated by mouse movement)
4086                         if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4087                                 // Move 1 item
4088                                 // TODO: middle mouse to move 10 items might be handy
4089                                 if (m_auto_place) {
4090                                         // Only move an item if the destination slot is empty
4091                                         // or contains the same item type as what is going to be
4092                                         // moved
4093                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4094                                         InventoryList *list_to = list_s;
4095                                         assert(list_from && list_to);
4096                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4097                                         ItemStack stack_to = list_to->getItem(s.i);
4098                                         if (stack_to.empty() || stack_to.name == stack_from.name)
4099                                                 move_amount = 1;
4100                                 }
4101                         }
4102                 break;
4103                 default:
4104                         break;
4105                 }
4106
4107                 // Possibly send inventory action to server
4108                 if (move_amount > 0) {
4109                         // Send IAction::Move
4110
4111                         assert(m_selected_item && m_selected_item->isValid());
4112                         assert(s.isValid());
4113
4114                         assert(inv_selected && inv_s);
4115                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4116                         InventoryList *list_to = list_s;
4117                         assert(list_from && list_to);
4118                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4119                         ItemStack stack_to = list_to->getItem(s.i);
4120
4121                         // Check how many items can be moved
4122                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4123                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4124                         bool move = true;
4125                         // If source stack cannot be added to destination stack at all,
4126                         // they are swapped
4127                         if (leftover.count == stack_from.count &&
4128                                         leftover.name == stack_from.name) {
4129
4130                                 if (m_selected_swap.empty()) {
4131                                         m_selected_amount = stack_to.count;
4132                                         m_selected_dragging = false;
4133
4134                                         // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4135                                         // Skip next validation checks due async inventory calls
4136                                         m_selected_swap = stack_to;
4137                                 } else {
4138                                         move = false;
4139                                 }
4140                         }
4141                         // Source stack goes fully into destination stack
4142                         else if (leftover.empty()) {
4143                                 m_selected_amount -= move_amount;
4144                         }
4145                         // Source stack goes partly into destination stack
4146                         else {
4147                                 move_amount -= leftover.count;
4148                                 m_selected_amount -= move_amount;
4149                         }
4150
4151                         if (move) {
4152                                 infostream << "Handing IAction::Move to manager" << std::endl;
4153                                 IMoveAction *a = new IMoveAction();
4154                                 a->count = move_amount;
4155                                 a->from_inv = m_selected_item->inventoryloc;
4156                                 a->from_list = m_selected_item->listname;
4157                                 a->from_i = m_selected_item->i;
4158                                 a->to_inv = s.inventoryloc;
4159                                 a->to_list = s.listname;
4160                                 a->to_i = s.i;
4161                                 m_invmgr->inventoryAction(a);
4162                         }
4163                 } else if (shift_move_amount > 0) {
4164                         u32 mis = m_inventory_rings.size();
4165                         u32 i = 0;
4166                         for (; i < mis; i++) {
4167                                 const ListRingSpec &sp = m_inventory_rings[i];
4168                                 if (sp.inventoryloc == s.inventoryloc
4169                                                 && sp.listname == s.listname)
4170                                         break;
4171                         }
4172                         do {
4173                                 if (i >= mis) // if not found
4174                                         break;
4175                                 u32 to_inv_ind = (i + 1) % mis;
4176                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4177                                 InventoryList *list_from = list_s;
4178                                 if (!s.isValid())
4179                                         break;
4180                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4181                                 if (!inv_to)
4182                                         break;
4183                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4184                                 if (!list_to)
4185                                         break;
4186                                 ItemStack stack_from = list_from->getItem(s.i);
4187                                 assert(shift_move_amount <= stack_from.count);
4188
4189                                 infostream << "Handing IAction::Move to manager" << std::endl;
4190                                 IMoveAction *a = new IMoveAction();
4191                                 a->count = shift_move_amount;
4192                                 a->from_inv = s.inventoryloc;
4193                                 a->from_list = s.listname;
4194                                 a->from_i = s.i;
4195                                 a->to_inv = to_inv_sp.inventoryloc;
4196                                 a->to_list = to_inv_sp.listname;
4197                                 a->move_somewhere = true;
4198                                 m_invmgr->inventoryAction(a);
4199                         } while (0);
4200                 } else if (drop_amount > 0) {
4201                         // Send IAction::Drop
4202
4203                         assert(m_selected_item && m_selected_item->isValid());
4204                         assert(inv_selected);
4205                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4206                         assert(list_from);
4207                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4208
4209                         // Check how many items can be dropped
4210                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4211                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4212                         m_selected_amount -= drop_amount;
4213
4214                         infostream << "Handing IAction::Drop to manager" << std::endl;
4215                         IDropAction *a = new IDropAction();
4216                         a->count = drop_amount;
4217                         a->from_inv = m_selected_item->inventoryloc;
4218                         a->from_list = m_selected_item->listname;
4219                         a->from_i = m_selected_item->i;
4220                         m_invmgr->inventoryAction(a);
4221                 } else if (craft_amount > 0) {
4222                         assert(s.isValid());
4223
4224                         // if there are no items selected or the selected item
4225                         // belongs to craftresult list, proceed with crafting
4226                         if (m_selected_item == NULL ||
4227                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4228
4229                                 assert(inv_s);
4230
4231                                 // Send IACTION_CRAFT
4232                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4233                                 ICraftAction *a = new ICraftAction();
4234                                 a->count = craft_amount;
4235                                 a->craft_inv = s.inventoryloc;
4236                                 m_invmgr->inventoryAction(a);
4237                         }
4238                 }
4239
4240                 // If m_selected_amount has been decreased to zero, deselect
4241                 if (m_selected_amount == 0) {
4242                         m_selected_swap.clear();
4243                         delete m_selected_item;
4244                         m_selected_item = NULL;
4245                         m_selected_amount = 0;
4246                         m_selected_dragging = false;
4247                 }
4248                 m_old_pointer = m_pointer;
4249         }
4250
4251         if (event.EventType == EET_GUI_EVENT) {
4252                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4253                                 && isVisible()) {
4254                         // find the element that was clicked
4255                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4256                                 if ((s.ftype == f_TabHeader) &&
4257                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4258                                         s.send = true;
4259                                         acceptInput();
4260                                         s.send = false;
4261                                         return true;
4262                                 }
4263                         }
4264                 }
4265                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4266                                 && isVisible()) {
4267                         if (!canTakeFocus(event.GUIEvent.Element)) {
4268                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4269                                                 <<std::endl;
4270                                 // Returning true disables focus change
4271                                 return true;
4272                         }
4273                 }
4274                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4275                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4276                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4277                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4278                         unsigned int btn_id = event.GUIEvent.Caller->getID();
4279
4280                         if (btn_id == 257) {
4281                                 if (m_allowclose) {
4282                                         acceptInput(quit_mode_accept);
4283                                         quitMenu();
4284                                 } else {
4285                                         acceptInput();
4286                                         m_text_dst->gotText(L"ExitButton");
4287                                 }
4288                                 // quitMenu deallocates menu
4289                                 return true;
4290                         }
4291
4292                         // find the element that was clicked
4293                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4294                                 // if its a button, set the send field so
4295                                 // lua knows which button was pressed
4296                                 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
4297                                                 s.fid == event.GUIEvent.Caller->getID()) {
4298                                         s.send = true;
4299                                         if (s.is_exit) {
4300                                                 if (m_allowclose) {
4301                                                         acceptInput(quit_mode_accept);
4302                                                         quitMenu();
4303                                                 } else {
4304                                                         m_text_dst->gotText(L"ExitButton");
4305                                                 }
4306                                                 return true;
4307                                         }
4308
4309                                         acceptInput(quit_mode_no);
4310                                         s.send = false;
4311                                         return true;
4312
4313                                 } else if ((s.ftype == f_DropDown) &&
4314                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4315                                         // only send the changed dropdown
4316                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4317                                                 if (s2.ftype == f_DropDown) {
4318                                                         s2.send = false;
4319                                                 }
4320                                         }
4321                                         s.send = true;
4322                                         acceptInput(quit_mode_no);
4323
4324                                         // revert configuration to make sure dropdowns are sent on
4325                                         // regular button click
4326                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4327                                                 if (s2.ftype == f_DropDown) {
4328                                                         s2.send = true;
4329                                                 }
4330                                         }
4331                                         return true;
4332                                 } else if ((s.ftype == f_ScrollBar) &&
4333                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4334                                         s.fdefault = L"Changed";
4335                                         acceptInput(quit_mode_no);
4336                                         s.fdefault = L"";
4337                                 } else if ((s.ftype == f_Unknown) &&
4338                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4339                                         s.send = true;
4340                                         acceptInput();
4341                                         s.send = false;
4342                                 }
4343                         }
4344                 }
4345
4346                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4347                         if (event.GUIEvent.Caller->getID() > 257) {
4348                                 bool close_on_enter = true;
4349                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4350                                         if (s.ftype == f_Unknown &&
4351                                                         s.fid == event.GUIEvent.Caller->getID()) {
4352                                                 current_field_enter_pending = s.fname;
4353                                                 std::unordered_map<std::string, bool>::const_iterator it =
4354                                                         field_close_on_enter.find(s.fname);
4355                                                 if (it != field_close_on_enter.end())
4356                                                         close_on_enter = (*it).second;
4357
4358                                                 break;
4359                                         }
4360                                 }
4361
4362                                 if (m_allowclose && close_on_enter) {
4363                                         current_keys_pending.key_enter = true;
4364                                         acceptInput(quit_mode_accept);
4365                                         quitMenu();
4366                                 } else {
4367                                         current_keys_pending.key_enter = true;
4368                                         acceptInput();
4369                                 }
4370                                 // quitMenu deallocates menu
4371                                 return true;
4372                         }
4373                 }
4374
4375                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4376                         int current_id = event.GUIEvent.Caller->getID();
4377                         if (current_id > 257) {
4378                                 // find the element that was clicked
4379                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4380                                         // if it's a table, set the send field
4381                                         // so lua knows which table was changed
4382                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
4383                                                 s.send = true;
4384                                                 acceptInput();
4385                                                 s.send=false;
4386                                         }
4387                                 }
4388                                 return true;
4389                         }
4390                 }
4391         }
4392
4393         return Parent ? Parent->OnEvent(event) : false;
4394 }
4395
4396 /**
4397  * get name of element by element id
4398  * @param id of element
4399  * @return name string or empty string
4400  */
4401 std::string GUIFormSpecMenu::getNameByID(s32 id)
4402 {
4403         for (FieldSpec &spec : m_fields) {
4404                 if (spec.fid == id)
4405                         return spec.fname;
4406         }
4407         return "";
4408 }
4409
4410
4411 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4412 {
4413         for (FieldSpec &spec : m_fields) {
4414                 if (spec.fid == id)
4415                         return &spec;
4416         }
4417         return nullptr;
4418 }
4419
4420 /**
4421  * get label of element by id
4422  * @param id of element
4423  * @return label string or empty string
4424  */
4425 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4426 {
4427         for (FieldSpec &spec : m_fields) {
4428                 if (spec.fid == id)
4429                         return spec.flabel;
4430         }
4431         return L"";
4432 }
4433
4434 StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
4435                 const std::string &name, const std::string &parent_type) {
4436         StyleSpec ret;
4437
4438         if (!parent_type.empty()) {
4439                 auto it = theme_by_type.find(parent_type);
4440                 if (it != theme_by_type.end()) {
4441                         ret |= it->second;
4442                 }
4443         }
4444
4445         auto it = theme_by_type.find(type);
4446         if (it != theme_by_type.end()) {
4447                 ret |= it->second;
4448         }
4449
4450         it = theme_by_name.find(name);
4451         if (it != theme_by_name.end()) {
4452                 ret |= it->second;
4453         }
4454
4455         return ret;
4456 }