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