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