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