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