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