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