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