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