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