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