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