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