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