Fix irrlicht version checking macro for tooltip_height calculation
[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(unescape_string(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(unescape_string(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_enriched(unescape_string(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_enriched(unescape_string(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_enriched(unescape_string(
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(unescape_string(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(unescape_string(label));
1013
1014         FieldSpec spec(
1015                 name,
1016                 wlabel,
1017                 utf8_to_wide(unescape_string(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(unescape_string(label));
1109
1110         FieldSpec spec(
1111                 name,
1112                 wlabel,
1113                 utf8_to_wide(unescape_string(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(unescape_string(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_enriched(
1254                         unescape_string(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(unescape_string(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_enriched(unescape_string(
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                 label = unescape_string(label);
1477                 item_name = unescape_string(item_name);
1478
1479                 MY_CHECKPOS("itemimagebutton",0);
1480                 MY_CHECKGEOM("itemimagebutton",1);
1481
1482                 v2s32 pos = padding;
1483                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1484                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1485                 v2s32 geom;
1486                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1487                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1488
1489                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1490
1491                 if(!data->explicit_size)
1492                         warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
1493
1494                 IItemDefManager *idef = m_gamedef->idef();
1495                 ItemStack item;
1496                 item.deSerialize(item_name, idef);
1497
1498                 m_tooltips[name] =
1499                         TooltipSpec(item.getDefinition(idef).description,
1500                                                 m_default_tooltip_bgcolor,
1501                                                 m_default_tooltip_color);
1502
1503                 FieldSpec spec(
1504                         name,
1505                         utf8_to_wide(label),
1506                         utf8_to_wide(item_name),
1507                         258 + m_fields.size()
1508                 );
1509
1510                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, L"");
1511
1512                 if (spec.fname == data->focused_fieldname) {
1513                         Environment->setFocus(e);
1514                 }
1515
1516                 spec.ftype = f_Button;
1517                 rect+=data->basepos-padding;
1518                 spec.rect=rect;
1519                 m_fields.push_back(spec);
1520                 pos = padding + AbsoluteRect.UpperLeftCorner;
1521                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1522                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1523                 m_itemimages.push_back(ImageDrawSpec("", item_name, e, pos, geom));
1524                 m_static_texts.push_back(StaticTextSpec(utf8_to_wide(label), rect, e));
1525                 return;
1526         }
1527         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1528 }
1529
1530 void GUIFormSpecMenu::parseBox(parserData* data,std::string element)
1531 {
1532         std::vector<std::string> parts = split(element,';');
1533
1534         if ((parts.size() == 3) ||
1535                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
1536         {
1537                 std::vector<std::string> v_pos = split(parts[0],',');
1538                 std::vector<std::string> v_geom = split(parts[1],',');
1539
1540                 MY_CHECKPOS("box",0);
1541                 MY_CHECKGEOM("box",1);
1542
1543                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
1544                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1545                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1546
1547                 v2s32 geom;
1548                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1549                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1550
1551                 video::SColor tmp_color;
1552
1553                 if (parseColorString(parts[2], tmp_color, false)) {
1554                         BoxDrawSpec spec(pos, geom, tmp_color);
1555
1556                         m_boxes.push_back(spec);
1557                 }
1558                 else {
1559                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1560                 }
1561                 return;
1562         }
1563         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1564 }
1565
1566 void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element)
1567 {
1568         std::vector<std::string> parts = split(element,';');
1569
1570         if (((parts.size() == 1) || (parts.size() == 2)) ||
1571                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1572         {
1573                 parseColorString(parts[0],m_bgcolor,false);
1574
1575                 if (parts.size() == 2) {
1576                         std::string fullscreen = parts[1];
1577                         m_bgfullscreen = is_yes(fullscreen);
1578                 }
1579                 return;
1580         }
1581         errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"  << std::endl;
1582 }
1583
1584 void GUIFormSpecMenu::parseListColors(parserData* data,std::string element)
1585 {
1586         std::vector<std::string> parts = split(element,';');
1587
1588         if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
1589                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1590         {
1591                 parseColorString(parts[0], m_slotbg_n, false);
1592                 parseColorString(parts[1], m_slotbg_h, false);
1593
1594                 if (parts.size() >= 3) {
1595                         if (parseColorString(parts[2], m_slotbordercolor, false)) {
1596                                 m_slotborder = true;
1597                         }
1598                 }
1599                 if (parts.size() == 5) {
1600                         video::SColor tmp_color;
1601
1602                         if (parseColorString(parts[3], tmp_color, false))
1603                                 m_default_tooltip_bgcolor = tmp_color;
1604                         if (parseColorString(parts[4], tmp_color, false))
1605                                 m_default_tooltip_color = tmp_color;
1606                 }
1607                 return;
1608         }
1609         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1610 }
1611
1612 void GUIFormSpecMenu::parseTooltip(parserData* data, std::string element)
1613 {
1614         std::vector<std::string> parts = split(element,';');
1615         if (parts.size() == 2) {
1616                 std::string name = parts[0];
1617                 m_tooltips[name] = TooltipSpec(unescape_string(parts[1]),
1618                         m_default_tooltip_bgcolor, m_default_tooltip_color);
1619                 return;
1620         } else if (parts.size() == 4) {
1621                 std::string name = parts[0];
1622                 video::SColor tmp_color1, tmp_color2;
1623                 if ( parseColorString(parts[2], tmp_color1, false) && parseColorString(parts[3], tmp_color2, false) ) {
1624                         m_tooltips[name] = TooltipSpec(unescape_string(parts[1]),
1625                                 tmp_color1, tmp_color2);
1626                         return;
1627                 }
1628         }
1629         errorstream<< "Invalid tooltip element(" << parts.size() << "): '" << element << "'"  << std::endl;
1630 }
1631
1632 bool GUIFormSpecMenu::parseVersionDirect(std::string data)
1633 {
1634         //some prechecks
1635         if (data == "")
1636                 return false;
1637
1638         std::vector<std::string> parts = split(data,'[');
1639
1640         if (parts.size() < 2) {
1641                 return false;
1642         }
1643
1644         if (parts[0] != "formspec_version") {
1645                 return false;
1646         }
1647
1648         if (is_number(parts[1])) {
1649                 m_formspec_version = mystoi(parts[1]);
1650                 return true;
1651         }
1652
1653         return false;
1654 }
1655
1656 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, std::string element)
1657 {
1658         if (element == "")
1659                 return false;
1660
1661         std::vector<std::string> parts = split(element,'[');
1662
1663         if (parts.size() < 2)
1664                 return false;
1665
1666         std::string type = trim(parts[0]);
1667         std::string description = trim(parts[1]);
1668
1669         if (type != "size" && type != "invsize")
1670                 return false;
1671
1672         if (type == "invsize")
1673                 log_deprecated("Deprecated formspec element \"invsize\" is used");
1674
1675         parseSize(data, description);
1676
1677         return true;
1678 }
1679
1680 void GUIFormSpecMenu::parseElement(parserData* data, std::string element)
1681 {
1682         //some prechecks
1683         if (element == "")
1684                 return;
1685
1686         std::vector<std::string> parts = split(element,'[');
1687
1688         // ugly workaround to keep compatibility
1689         if (parts.size() > 2) {
1690                 if (trim(parts[0]) == "image") {
1691                         for (unsigned int i=2;i< parts.size(); i++) {
1692                                 parts[1] += "[" + parts[i];
1693                         }
1694                 }
1695                 else { return; }
1696         }
1697
1698         if (parts.size() < 2) {
1699                 return;
1700         }
1701
1702         std::string type = trim(parts[0]);
1703         std::string description = trim(parts[1]);
1704
1705         if (type == "list") {
1706                 parseList(data,description);
1707                 return;
1708         }
1709
1710         if (type == "listring") {
1711                 parseListRing(data, description);
1712                 return;
1713         }
1714
1715         if (type == "checkbox") {
1716                 parseCheckbox(data,description);
1717                 return;
1718         }
1719
1720         if (type == "image") {
1721                 parseImage(data,description);
1722                 return;
1723         }
1724
1725         if (type == "item_image") {
1726                 parseItemImage(data,description);
1727                 return;
1728         }
1729
1730         if ((type == "button") || (type == "button_exit")) {
1731                 parseButton(data,description,type);
1732                 return;
1733         }
1734
1735         if (type == "background") {
1736                 parseBackground(data,description);
1737                 return;
1738         }
1739
1740         if (type == "tableoptions"){
1741                 parseTableOptions(data,description);
1742                 return;
1743         }
1744
1745         if (type == "tablecolumns"){
1746                 parseTableColumns(data,description);
1747                 return;
1748         }
1749
1750         if (type == "table"){
1751                 parseTable(data,description);
1752                 return;
1753         }
1754
1755         if (type == "textlist"){
1756                 parseTextList(data,description);
1757                 return;
1758         }
1759
1760         if (type == "dropdown"){
1761                 parseDropDown(data,description);
1762                 return;
1763         }
1764
1765         if (type == "pwdfield") {
1766                 parsePwdField(data,description);
1767                 return;
1768         }
1769
1770         if ((type == "field") || (type == "textarea")){
1771                 parseField(data,description,type);
1772                 return;
1773         }
1774
1775         if (type == "label") {
1776                 parseLabel(data,description);
1777                 return;
1778         }
1779
1780         if (type == "vertlabel") {
1781                 parseVertLabel(data,description);
1782                 return;
1783         }
1784
1785         if (type == "item_image_button") {
1786                 parseItemImageButton(data,description);
1787                 return;
1788         }
1789
1790         if ((type == "image_button") || (type == "image_button_exit")) {
1791                 parseImageButton(data,description,type);
1792                 return;
1793         }
1794
1795         if (type == "tabheader") {
1796                 parseTabHeader(data,description);
1797                 return;
1798         }
1799
1800         if (type == "box") {
1801                 parseBox(data,description);
1802                 return;
1803         }
1804
1805         if (type == "bgcolor") {
1806                 parseBackgroundColor(data,description);
1807                 return;
1808         }
1809
1810         if (type == "listcolors") {
1811                 parseListColors(data,description);
1812                 return;
1813         }
1814
1815         if (type == "tooltip") {
1816                 parseTooltip(data,description);
1817                 return;
1818         }
1819
1820         if (type == "scrollbar") {
1821                 parseScrollBar(data, description);
1822                 return;
1823         }
1824
1825         // Ignore others
1826         infostream
1827                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1828                 <<std::endl;
1829 }
1830
1831 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1832 {
1833         /* useless to regenerate without a screensize */
1834         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
1835                 return;
1836         }
1837
1838         parserData mydata;
1839
1840         //preserve tables
1841         for (u32 i = 0; i < m_tables.size(); ++i) {
1842                 std::string tablename = m_tables[i].first.fname;
1843                 GUITable *table = m_tables[i].second;
1844                 mydata.table_dyndata[tablename] = table->getDynamicData();
1845         }
1846
1847         //set focus
1848         if (!m_focused_element.empty())
1849                 mydata.focused_fieldname = m_focused_element;
1850
1851         //preserve focus
1852         gui::IGUIElement *focused_element = Environment->getFocus();
1853         if (focused_element && focused_element->getParent() == this) {
1854                 s32 focused_id = focused_element->getID();
1855                 if (focused_id > 257) {
1856                         for (u32 i=0; i<m_fields.size(); i++) {
1857                                 if (m_fields[i].fid == focused_id) {
1858                                         mydata.focused_fieldname =
1859                                                 m_fields[i].fname;
1860                                         break;
1861                                 }
1862                         }
1863                 }
1864         }
1865
1866         // Remove children
1867         removeChildren();
1868
1869         for (u32 i = 0; i < m_tables.size(); ++i) {
1870                 GUITable *table = m_tables[i].second;
1871                 table->drop();
1872         }
1873
1874         mydata.size= v2s32(100,100);
1875         mydata.screensize = screensize;
1876
1877         // Base position of contents of form
1878         mydata.basepos = getBasePos();
1879
1880         /* Convert m_init_draw_spec to m_inventorylists */
1881
1882         m_inventorylists.clear();
1883         m_images.clear();
1884         m_backgrounds.clear();
1885         m_itemimages.clear();
1886         m_tables.clear();
1887         m_checkboxes.clear();
1888         m_scrollbars.clear();
1889         m_fields.clear();
1890         m_boxes.clear();
1891         m_tooltips.clear();
1892         m_inventory_rings.clear();
1893         m_static_texts.clear();
1894
1895         // Set default values (fits old formspec values)
1896         m_bgcolor = video::SColor(140,0,0,0);
1897         m_bgfullscreen = false;
1898
1899         m_slotbg_n = video::SColor(255,128,128,128);
1900         m_slotbg_h = video::SColor(255,192,192,192);
1901
1902         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
1903         m_default_tooltip_color = video::SColor(255,255,255,255);
1904
1905         m_slotbordercolor = video::SColor(200,0,0,0);
1906         m_slotborder = false;
1907
1908         m_clipbackground = false;
1909         // Add tooltip
1910         {
1911                 assert(m_tooltip_element == NULL);
1912                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
1913                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
1914                 m_tooltip_element->enableOverrideColor(true);
1915                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
1916                 m_tooltip_element->setDrawBackground(true);
1917                 m_tooltip_element->setDrawBorder(true);
1918                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
1919                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1920                 m_tooltip_element->setWordWrap(false);
1921                 //we're not parent so no autograb for this one!
1922                 m_tooltip_element->grab();
1923         }
1924
1925         std::vector<std::string> elements = split(m_formspec_string,']');
1926         unsigned int i = 0;
1927
1928         /* try to read version from first element only */
1929         if (elements.size() >= 1) {
1930                 if ( parseVersionDirect(elements[0]) ) {
1931                         i++;
1932                 }
1933         }
1934
1935         /* we need size first in order to calculate image scale */
1936         mydata.explicit_size = false;
1937         for (; i< elements.size(); i++) {
1938                 if (!parseSizeDirect(&mydata, elements[i])) {
1939                         break;
1940                 }
1941         }
1942
1943         if (mydata.explicit_size) {
1944                 // compute scaling for specified form size
1945                 if (m_lock) {
1946                         v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize();
1947                         v2u32 delta = current_screensize - m_lockscreensize;
1948
1949                         if (current_screensize.Y > m_lockscreensize.Y)
1950                                 delta.Y /= 2;
1951                         else
1952                                 delta.Y = 0;
1953
1954                         if (current_screensize.X > m_lockscreensize.X)
1955                                 delta.X /= 2;
1956                         else
1957                                 delta.X = 0;
1958
1959                         offset = v2s32(delta.X,delta.Y);
1960
1961                         mydata.screensize = m_lockscreensize;
1962                 } else {
1963                         offset = v2s32(0,0);
1964                 }
1965
1966                 double gui_scaling = g_settings->getFloat("gui_scaling");
1967                 double screen_dpi = porting::getDisplayDensity() * 96;
1968
1969                 double use_imgsize;
1970                 if (m_lock) {
1971                         // In fixed-size mode, inventory image size
1972                         // is 0.53 inch multiplied by the gui_scaling
1973                         // config parameter.  This magic size is chosen
1974                         // to make the main menu (15.5 inventory images
1975                         // wide, including border) just fit into the
1976                         // default window (800 pixels wide) at 96 DPI
1977                         // and default scaling (1.00).
1978                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
1979                 } else {
1980                         // In variable-size mode, we prefer to make the
1981                         // inventory image size 1/15 of screen height,
1982                         // multiplied by the gui_scaling config parameter.
1983                         // If the preferred size won't fit the whole
1984                         // form on the screen, either horizontally or
1985                         // vertically, then we scale it down to fit.
1986                         // (The magic numbers in the computation of what
1987                         // fits arise from the scaling factors in the
1988                         // following stanza, including the form border,
1989                         // help text space, and 0.1 inventory slot spare.)
1990                         // However, a minimum size is also set, that
1991                         // the image size can't be less than 0.3 inch
1992                         // multiplied by gui_scaling, even if this means
1993                         // the form doesn't fit the screen.
1994                         double prefer_imgsize = mydata.screensize.Y / 15 *
1995                                                         gui_scaling;
1996                         double fitx_imgsize = mydata.screensize.X /
1997                                 ((5.0/4.0) * (0.5 + mydata.invsize.X));
1998                         double fity_imgsize = mydata.screensize.Y /
1999                                 ((15.0/13.0) * (0.85 * mydata.invsize.Y));
2000                         double screen_dpi = porting::getDisplayDensity() * 96;
2001                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2002                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2003                                 MYMIN(fitx_imgsize, fity_imgsize)));
2004                 }
2005
2006                 // Everything else is scaled in proportion to the
2007                 // inventory image size.  The inventory slot spacing
2008                 // is 5/4 image size horizontally and 15/13 image size
2009                 // vertically.  The padding around the form (incorporating
2010                 // the border of the outer inventory slots) is 3/8
2011                 // image size.  Font height (baseline to baseline)
2012                 // is 2/5 vertical inventory slot spacing, and button
2013                 // half-height is 7/8 of font height.
2014                 imgsize = v2s32(use_imgsize, use_imgsize);
2015                 spacing = v2s32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2016                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2017                 m_btn_height = use_imgsize*15.0/13 * 0.35;
2018
2019                 m_font = g_fontengine->getFont();
2020
2021                 mydata.size = v2s32(
2022                         padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2023                         padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2024                 );
2025                 DesiredRect = mydata.rect = core::rect<s32>(
2026                                 mydata.screensize.X/2 - mydata.size.X/2 + offset.X,
2027                                 mydata.screensize.Y/2 - mydata.size.Y/2 + offset.Y,
2028                                 mydata.screensize.X/2 + mydata.size.X/2 + offset.X,
2029                                 mydata.screensize.Y/2 + mydata.size.Y/2 + offset.Y
2030                 );
2031         } else {
2032                 // Non-size[] form must consist only of text fields and
2033                 // implicit "Proceed" button.  Use default font, and
2034                 // temporary form size which will be recalculated below.
2035                 m_font = g_fontengine->getFont();
2036                 m_btn_height = font_line_height(m_font) * 0.875;
2037                 DesiredRect = core::rect<s32>(
2038                         mydata.screensize.X/2 - 580/2,
2039                         mydata.screensize.Y/2 - 300/2,
2040                         mydata.screensize.X/2 + 580/2,
2041                         mydata.screensize.Y/2 + 300/2
2042                 );
2043         }
2044         recalculateAbsolutePosition(false);
2045         mydata.basepos = getBasePos();
2046         m_tooltip_element->setOverrideFont(m_font);
2047
2048         gui::IGUISkin* skin = Environment->getSkin();
2049         sanity_check(skin != NULL);
2050         gui::IGUIFont *old_font = skin->getFont();
2051         skin->setFont(m_font);
2052
2053         for (; i< elements.size(); i++) {
2054                 parseElement(&mydata, elements[i]);
2055         }
2056
2057         // If there are fields without explicit size[], add a "Proceed"
2058         // button and adjust size to fit all the fields.
2059         if (m_fields.size() && !mydata.explicit_size) {
2060                 mydata.rect = core::rect<s32>(
2061                                 mydata.screensize.X/2 - 580/2,
2062                                 mydata.screensize.Y/2 - 300/2,
2063                                 mydata.screensize.X/2 + 580/2,
2064                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
2065                 );
2066                 DesiredRect = mydata.rect;
2067                 recalculateAbsolutePosition(false);
2068                 mydata.basepos = getBasePos();
2069
2070                 {
2071                         v2s32 pos = mydata.basepos;
2072                         pos.Y = ((m_fields.size()+2)*60);
2073
2074                         v2s32 size = DesiredRect.getSize();
2075                         mydata.rect =
2076                                         core::rect<s32>(size.X/2-70, pos.Y,
2077                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2078                         const wchar_t *text = wgettext("Proceed");
2079                         Environment->addButton(mydata.rect, this, 257, text);
2080                         delete[] text;
2081                 }
2082
2083         }
2084
2085         //set initial focus if parser didn't set it
2086         focused_element = Environment->getFocus();
2087         if (!focused_element
2088                         || !isMyChild(focused_element)
2089                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2090                 setInitialFocus();
2091
2092         skin->setFont(old_font);
2093 }
2094
2095 #ifdef __ANDROID__
2096 bool GUIFormSpecMenu::getAndroidUIInput()
2097 {
2098         /* no dialog shown */
2099         if (m_JavaDialogFieldName == "") {
2100                 return false;
2101         }
2102
2103         /* still waiting */
2104         if (porting::getInputDialogState() == -1) {
2105                 return true;
2106         }
2107
2108         std::string fieldname = m_JavaDialogFieldName;
2109         m_JavaDialogFieldName = "";
2110
2111         /* no value abort dialog processing */
2112         if (porting::getInputDialogState() != 0) {
2113                 return false;
2114         }
2115
2116         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2117                         iter != m_fields.end(); ++iter) {
2118
2119                 if (iter->fname != fieldname) {
2120                         continue;
2121                 }
2122                 IGUIElement* tochange = getElementFromId(iter->fid);
2123
2124                 if (tochange == 0) {
2125                         return false;
2126                 }
2127
2128                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2129                         return false;
2130                 }
2131
2132                 std::string text = porting::getInputDialogValue();
2133
2134                 ((gui::IGUIEditBox*) tochange)->
2135                         setText(utf8_to_wide(text).c_str());
2136         }
2137         return false;
2138 }
2139 #endif
2140
2141 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2142 {
2143         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2144
2145         for(u32 i=0; i<m_inventorylists.size(); i++)
2146         {
2147                 const ListDrawSpec &s = m_inventorylists[i];
2148
2149                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2150                         s32 item_i = i + s.start_item_i;
2151                         s32 x = (i%s.geom.X) * spacing.X;
2152                         s32 y = (i/s.geom.X) * spacing.Y;
2153                         v2s32 p0(x,y);
2154                         core::rect<s32> rect = imgrect + s.pos + p0;
2155                         if(rect.isPointInside(p))
2156                         {
2157                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2158                         }
2159                 }
2160         }
2161
2162         return ItemSpec(InventoryLocation(), "", -1);
2163 }
2164
2165 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase,
2166                 bool &item_hovered)
2167 {
2168         video::IVideoDriver* driver = Environment->getVideoDriver();
2169
2170         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2171         if(!inv){
2172                 warningstream<<"GUIFormSpecMenu::drawList(): "
2173                                 <<"The inventory location "
2174                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2175                                 <<std::endl;
2176                 return;
2177         }
2178         InventoryList *ilist = inv->getList(s.listname);
2179         if(!ilist){
2180                 warningstream<<"GUIFormSpecMenu::drawList(): "
2181                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2182                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2183                                 <<std::endl;
2184                 return;
2185         }
2186
2187         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2188
2189         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
2190         {
2191                 s32 item_i = i + s.start_item_i;
2192                 if(item_i >= (s32) ilist->getSize())
2193                         break;
2194                 s32 x = (i%s.geom.X) * spacing.X;
2195                 s32 y = (i/s.geom.X) * spacing.Y;
2196                 v2s32 p(x,y);
2197                 core::rect<s32> rect = imgrect + s.pos + p;
2198                 ItemStack item;
2199                 if(ilist)
2200                         item = ilist->getItem(item_i);
2201
2202                 bool selected = m_selected_item
2203                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2204                         && m_selected_item->listname == s.listname
2205                         && m_selected_item->i == item_i;
2206                 bool hovering = rect.isPointInside(m_pointer);
2207                 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
2208                         (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
2209
2210                 if (phase == 0) {
2211                         if (hovering) {
2212                                 item_hovered = true;
2213                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2214                         } else {
2215                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2216                         }
2217                 }
2218
2219                 //Draw inv slot borders
2220                 if (m_slotborder) {
2221                         s32 x1 = rect.UpperLeftCorner.X;
2222                         s32 y1 = rect.UpperLeftCorner.Y;
2223                         s32 x2 = rect.LowerRightCorner.X;
2224                         s32 y2 = rect.LowerRightCorner.Y;
2225                         s32 border = 1;
2226                         driver->draw2DRectangle(m_slotbordercolor,
2227                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2228                                                                 v2s32(x2 + border, y1)), NULL);
2229                         driver->draw2DRectangle(m_slotbordercolor,
2230                                 core::rect<s32>(v2s32(x1 - border, y2),
2231                                                                 v2s32(x2 + border, y2 + border)), NULL);
2232                         driver->draw2DRectangle(m_slotbordercolor,
2233                                 core::rect<s32>(v2s32(x1 - border, y1),
2234                                                                 v2s32(x1, y2)), NULL);
2235                         driver->draw2DRectangle(m_slotbordercolor,
2236                                 core::rect<s32>(v2s32(x2, y1),
2237                                                                 v2s32(x2 + border, y2)), NULL);
2238                 }
2239
2240                 if(phase == 1)
2241                 {
2242                         // Draw item stack
2243                         if(selected)
2244                         {
2245                                 item.takeItem(m_selected_amount);
2246                         }
2247                         if(!item.empty())
2248                         {
2249                                 drawItemStack(driver, m_font, item,
2250                                         rect, &AbsoluteClippingRect, m_gamedef,
2251                                         rotation_kind);
2252                         }
2253
2254                         // Draw tooltip
2255                         std::wstring tooltip_text = L"";
2256                         if (hovering && !m_selected_item) {
2257                                 tooltip_text = utf8_to_wide(item.getDefinition(m_gamedef->idef()).description);
2258                                 tooltip_text = unescape_enriched(tooltip_text);
2259                         }
2260                         if (tooltip_text != L"") {
2261                                 std::vector<std::wstring> tt_rows = str_split(tooltip_text, L'\n');
2262                                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2263                                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2264                                 m_tooltip_element->setVisible(true);
2265                                 this->bringToFront(m_tooltip_element);
2266                                 m_tooltip_element->setText(tooltip_text.c_str());
2267                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2268 #if IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2
2269                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2270 #else
2271                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
2272 #endif
2273                                 v2u32 screenSize = driver->getScreenSize();
2274                                 int tooltip_offset_x = m_btn_height;
2275                                 int tooltip_offset_y = m_btn_height;
2276 #ifdef __ANDROID__
2277                                 tooltip_offset_x *= 3;
2278                                 tooltip_offset_y  = 0;
2279                                 if (m_pointer.X > (s32)screenSize.X / 2)
2280                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2281 #endif
2282                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2283                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2284                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2285                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2286                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2287                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2288                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2289                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2290                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2291                         }
2292                 }
2293         }
2294 }
2295
2296 void GUIFormSpecMenu::drawSelectedItem()
2297 {
2298         video::IVideoDriver* driver = Environment->getVideoDriver();
2299
2300         if (!m_selected_item) {
2301                 drawItemStack(driver, m_font, ItemStack(),
2302                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
2303                         NULL, m_gamedef, IT_ROT_DRAGGED);
2304                 return;
2305         }
2306
2307         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2308         sanity_check(inv);
2309         InventoryList *list = inv->getList(m_selected_item->listname);
2310         sanity_check(list);
2311         ItemStack stack = list->getItem(m_selected_item->i);
2312         stack.count = m_selected_amount;
2313
2314         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2315         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2316         drawItemStack(driver, m_font, stack, rect, NULL, m_gamedef, IT_ROT_DRAGGED);
2317 }
2318
2319 void GUIFormSpecMenu::drawMenu()
2320 {
2321         if(m_form_src){
2322                 std::string newform = m_form_src->getForm();
2323                 if(newform != m_formspec_string){
2324                         m_formspec_string = newform;
2325                         regenerateGui(m_screensize_old);
2326                 }
2327         }
2328
2329         gui::IGUISkin* skin = Environment->getSkin();
2330         sanity_check(skin != NULL);
2331         gui::IGUIFont *old_font = skin->getFont();
2332         skin->setFont(m_font);
2333
2334         updateSelectedItem();
2335
2336         video::IVideoDriver* driver = Environment->getVideoDriver();
2337
2338         v2u32 screenSize = driver->getScreenSize();
2339         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
2340         if (m_bgfullscreen)
2341                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
2342         else
2343                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2344
2345         m_tooltip_element->setVisible(false);
2346
2347         /*
2348                 Draw backgrounds
2349         */
2350         for(u32 i=0; i<m_backgrounds.size(); i++)
2351         {
2352                 const ImageDrawSpec &spec = m_backgrounds[i];
2353                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2354
2355                 if (texture != 0) {
2356                         // Image size on screen
2357                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2358                         // Image rectangle on screen
2359                         core::rect<s32> rect = imgrect + spec.pos;
2360
2361                         if (m_clipbackground) {
2362                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2363                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2364                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2365                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2366                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2367                         }
2368
2369                         const video::SColor color(255,255,255,255);
2370                         const video::SColor colors[] = {color,color,color,color};
2371                         draw2DImageFilterScaled(driver, texture, rect,
2372                                 core::rect<s32>(core::position2d<s32>(0,0),
2373                                                 core::dimension2di(texture->getOriginalSize())),
2374                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2375                 }
2376                 else {
2377                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2378                         errorstream << "\t" << spec.name << std::endl;
2379                 }
2380         }
2381
2382         /*
2383                 Draw Boxes
2384         */
2385         for(u32 i=0; i<m_boxes.size(); i++)
2386         {
2387                 const BoxDrawSpec &spec = m_boxes[i];
2388
2389                 irr::video::SColor todraw = spec.color;
2390
2391                 todraw.setAlpha(140);
2392
2393                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2394                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2395
2396                 driver->draw2DRectangle(todraw, rect, 0);
2397         }
2398
2399         /*
2400                 Call base class
2401         */
2402         gui::IGUIElement::draw();
2403
2404         /*
2405                 Draw images
2406         */
2407         for(u32 i=0; i<m_images.size(); i++)
2408         {
2409                 const ImageDrawSpec &spec = m_images[i];
2410                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2411
2412                 if (texture != 0) {
2413                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2414                         // Image size on screen
2415                         core::rect<s32> imgrect;
2416
2417                         if (spec.scale)
2418                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2419                         else {
2420
2421                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2422                         }
2423                         // Image rectangle on screen
2424                         core::rect<s32> rect = imgrect + spec.pos;
2425                         const video::SColor color(255,255,255,255);
2426                         const video::SColor colors[] = {color,color,color,color};
2427                         draw2DImageFilterScaled(driver, texture, rect,
2428                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2429                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2430                 }
2431                 else {
2432                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2433                         errorstream << "\t" << spec.name << std::endl;
2434                 }
2435         }
2436
2437         /*
2438                 Draw item images
2439         */
2440         for(u32 i=0; i<m_itemimages.size(); i++)
2441         {
2442                 if (m_gamedef == 0)
2443                         break;
2444
2445                 const ImageDrawSpec &spec = m_itemimages[i];
2446                 IItemDefManager *idef = m_gamedef->idef();
2447                 ItemStack item;
2448                 item.deSerialize(spec.item_name, idef);
2449                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2450                 // Viewport rectangle on screen
2451                 core::rect<s32> rect = imgrect + spec.pos;
2452                 if (spec.parent_button && spec.parent_button->isPressed()) {
2453 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2454                         rect += core::dimension2d<s32>(
2455                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
2456 #else
2457                         rect += core::dimension2d<s32>(
2458                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
2459                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
2460 #endif
2461                 }
2462                 drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect,
2463                                 m_gamedef, IT_ROT_NONE);
2464         }
2465
2466         /*
2467                 Draw items
2468                 Phase 0: Item slot rectangles
2469                 Phase 1: Item images; prepare tooltip
2470         */
2471         bool item_hovered = false;
2472         int start_phase = 0;
2473         for (int phase = start_phase; phase <= 1; phase++) {
2474                 for (u32 i = 0; i < m_inventorylists.size(); i++) {
2475                         drawList(m_inventorylists[i], phase, item_hovered);
2476                 }
2477         }
2478         if (!item_hovered) {
2479                 drawItemStack(driver, m_font, ItemStack(),
2480                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
2481                         NULL, m_gamedef, IT_ROT_HOVERED);
2482         }
2483
2484 /* TODO find way to show tooltips on touchscreen */
2485 #ifndef HAVE_TOUCHSCREENGUI
2486         m_pointer = m_device->getCursorControl()->getPosition();
2487 #endif
2488
2489         /*
2490                 Draw static text elements
2491         */
2492         for (u32 i = 0; i < m_static_texts.size(); i++) {
2493                 const StaticTextSpec &spec = m_static_texts[i]; 
2494                 core::rect<s32> rect = spec.rect;
2495                 if (spec.parent_button && spec.parent_button->isPressed()) {
2496 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2497                         rect += core::dimension2d<s32>(
2498                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
2499 #else
2500                         // Use image offset instead of text's because its a bit smaller
2501                         // and fits better, also TEXT_OFFSET_X is always 0
2502                         rect += core::dimension2d<s32>(
2503                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
2504                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
2505 #endif
2506                 }
2507                 video::SColor color(255, 255, 255, 255);
2508                 m_font->draw(spec.text.c_str(), rect, color, true, true, &rect);
2509         }
2510
2511         /*
2512                 Draw fields/buttons tooltips
2513         */
2514         gui::IGUIElement *hovered =
2515                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2516
2517         if (hovered != NULL) {
2518                 s32 id = hovered->getID();
2519
2520                 u32 delta = 0;
2521                 if (id == -1) {
2522                         m_old_tooltip_id = id;
2523                         m_old_tooltip = L"";
2524                 } else {
2525                         if (id == m_old_tooltip_id) {
2526                                 delta = porting::getDeltaMs(m_hovered_time, getTimeMs());
2527                         } else {
2528                                 m_hovered_time = getTimeMs();
2529                                 m_old_tooltip_id = id;
2530                         }
2531                 }
2532
2533                 if (id != -1 && delta >= m_tooltip_show_delay) {
2534                         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2535                                         iter != m_fields.end(); ++iter) {
2536                                 if (iter->fid == id && m_tooltips[iter->fname].tooltip != L"") {
2537                                         if (m_old_tooltip != m_tooltips[iter->fname].tooltip) {
2538                                                 m_old_tooltip = m_tooltips[iter->fname].tooltip;
2539                                                 m_tooltip_element->setText(m_tooltips[iter->fname].tooltip.c_str());
2540                                                 std::vector<std::wstring> tt_rows = str_split(m_tooltips[iter->fname].tooltip, L'\n');
2541                                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2542                                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2543                                                 int tooltip_offset_x = m_btn_height;
2544                                                 int tooltip_offset_y = m_btn_height;
2545 #ifdef __ANDROID__
2546                                                 tooltip_offset_x *= 3;
2547                                                 tooltip_offset_y  = 0;
2548                                                 if (m_pointer.X > (s32)screenSize.X / 2)
2549                                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2550 #endif
2551                                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2552                                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2553                                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2554                                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2555                                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2556                                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2557                                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2558                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2559                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2560                                         }
2561                                         m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor);
2562                                         m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color);
2563                                         m_tooltip_element->setVisible(true);
2564                                         this->bringToFront(m_tooltip_element);
2565                                         break;
2566                                 }
2567                         }
2568                 }
2569         }
2570
2571         /*
2572                 Draw dragged item stack
2573         */
2574         drawSelectedItem();
2575
2576         skin->setFont(old_font);
2577 }
2578
2579 void GUIFormSpecMenu::updateSelectedItem()
2580 {
2581         // If the selected stack has become empty for some reason, deselect it.
2582         // If the selected stack has become inaccessible, deselect it.
2583         // If the selected stack has become smaller, adjust m_selected_amount.
2584         ItemStack selected = verifySelectedItem();
2585
2586         // WARNING: BLACK MAGIC
2587         // See if there is a stack suited for our current guess.
2588         // If such stack does not exist, clear the guess.
2589         if(m_selected_content_guess.name != "" &&
2590                         selected.name == m_selected_content_guess.name &&
2591                         selected.count == m_selected_content_guess.count){
2592                 // Selected item fits the guess. Skip the black magic.
2593         }
2594         else if(m_selected_content_guess.name != ""){
2595                 bool found = false;
2596                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2597                         const ListDrawSpec &s = m_inventorylists[i];
2598                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2599                         if(!inv)
2600                                 continue;
2601                         InventoryList *list = inv->getList(s.listname);
2602                         if(!list)
2603                                 continue;
2604                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2605                                 u32 item_i = i + s.start_item_i;
2606                                 if(item_i >= list->getSize())
2607                                         continue;
2608                                 ItemStack stack = list->getItem(item_i);
2609                                 if(stack.name == m_selected_content_guess.name &&
2610                                                 stack.count == m_selected_content_guess.count){
2611                                         found = true;
2612                                         infostream<<"Client: Changing selected content guess to "
2613                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2614                                                         <<" "<<item_i<<std::endl;
2615                                         delete m_selected_item;
2616                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2617                                         m_selected_amount = stack.count;
2618                                 }
2619                         }
2620                 }
2621                 if(!found){
2622                         infostream<<"Client: Discarding selected content guess: "
2623                                         <<m_selected_content_guess.getItemString()<<std::endl;
2624                         m_selected_content_guess.name = "";
2625                 }
2626         }
2627
2628         // If craftresult is nonempty and nothing else is selected, select it now.
2629         if(!m_selected_item)
2630         {
2631                 for(u32 i=0; i<m_inventorylists.size(); i++)
2632                 {
2633                         const ListDrawSpec &s = m_inventorylists[i];
2634                         if(s.listname == "craftpreview")
2635                         {
2636                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2637                                 InventoryList *list = inv->getList("craftresult");
2638                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2639                                 {
2640                                         m_selected_item = new ItemSpec;
2641                                         m_selected_item->inventoryloc = s.inventoryloc;
2642                                         m_selected_item->listname = "craftresult";
2643                                         m_selected_item->i = 0;
2644                                         m_selected_amount = 0;
2645                                         m_selected_dragging = false;
2646                                         break;
2647                                 }
2648                         }
2649                 }
2650         }
2651
2652         // If craftresult is selected, keep the whole stack selected
2653         if(m_selected_item && m_selected_item->listname == "craftresult")
2654         {
2655                 m_selected_amount = verifySelectedItem().count;
2656         }
2657 }
2658
2659 ItemStack GUIFormSpecMenu::verifySelectedItem()
2660 {
2661         // If the selected stack has become empty for some reason, deselect it.
2662         // If the selected stack has become inaccessible, deselect it.
2663         // If the selected stack has become smaller, adjust m_selected_amount.
2664         // Return the selected stack.
2665
2666         if(m_selected_item)
2667         {
2668                 if(m_selected_item->isValid())
2669                 {
2670                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2671                         if(inv)
2672                         {
2673                                 InventoryList *list = inv->getList(m_selected_item->listname);
2674                                 if(list && (u32) m_selected_item->i < list->getSize())
2675                                 {
2676                                         ItemStack stack = list->getItem(m_selected_item->i);
2677                                         if(m_selected_amount > stack.count)
2678                                                 m_selected_amount = stack.count;
2679                                         if(!stack.empty())
2680                                                 return stack;
2681                                 }
2682                         }
2683                 }
2684
2685                 // selection was not valid
2686                 delete m_selected_item;
2687                 m_selected_item = NULL;
2688                 m_selected_amount = 0;
2689                 m_selected_dragging = false;
2690         }
2691         return ItemStack();
2692 }
2693
2694 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2695 {
2696         if(m_text_dst)
2697         {
2698                 StringMap fields;
2699
2700                 if (quitmode == quit_mode_accept) {
2701                         fields["quit"] = "true";
2702                 }
2703
2704                 if (quitmode == quit_mode_cancel) {
2705                         fields["quit"] = "true";
2706                         m_text_dst->gotText(fields);
2707                         return;
2708                 }
2709
2710                 if (current_keys_pending.key_down) {
2711                         fields["key_down"] = "true";
2712                         current_keys_pending.key_down = false;
2713                 }
2714
2715                 if (current_keys_pending.key_up) {
2716                         fields["key_up"] = "true";
2717                         current_keys_pending.key_up = false;
2718                 }
2719
2720                 if (current_keys_pending.key_enter) {
2721                         fields["key_enter"] = "true";
2722                         current_keys_pending.key_enter = false;
2723                 }
2724
2725                 if (current_keys_pending.key_escape) {
2726                         fields["key_escape"] = "true";
2727                         current_keys_pending.key_escape = false;
2728                 }
2729
2730                 for(unsigned int i=0; i<m_fields.size(); i++) {
2731                         const FieldSpec &s = m_fields[i];
2732                         if(s.send) {
2733                                 std::string name = s.fname;
2734                                 if (s.ftype == f_Button) {
2735                                         fields[name] = wide_to_utf8(s.flabel);
2736                                 } else if (s.ftype == f_Table) {
2737                                         GUITable *table = getTable(s.fname);
2738                                         if (table) {
2739                                                 fields[name] = table->checkEvent();
2740                                         }
2741                                 }
2742                                 else if(s.ftype == f_DropDown) {
2743                                         // no dynamic cast possible due to some distributions shipped
2744                                         // without rtti support in irrlicht
2745                                         IGUIElement * element = getElementFromId(s.fid);
2746                                         gui::IGUIComboBox *e = NULL;
2747                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2748                                                 e = static_cast<gui::IGUIComboBox*>(element);
2749                                         }
2750                                         s32 selected = e->getSelected();
2751                                         if (selected >= 0) {
2752                                                 std::vector<std::string> *dropdown_values =
2753                                                         getDropDownValues(s.fname);
2754                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
2755                                                         fields[name] = (*dropdown_values)[selected];
2756                                                 }
2757                                         }
2758                                 }
2759                                 else if (s.ftype == f_TabHeader) {
2760                                         // no dynamic cast possible due to some distributions shipped
2761                                         // without rtti support in irrlicht
2762                                         IGUIElement * element = getElementFromId(s.fid);
2763                                         gui::IGUITabControl *e = NULL;
2764                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2765                                                 e = static_cast<gui::IGUITabControl*>(element);
2766                                         }
2767
2768                                         if (e != 0) {
2769                                                 std::stringstream ss;
2770                                                 ss << (e->getActiveTab() +1);
2771                                                 fields[name] = ss.str();
2772                                         }
2773                                 }
2774                                 else if (s.ftype == f_CheckBox) {
2775                                         // no dynamic cast possible due to some distributions shipped
2776                                         // without rtti support in irrlicht
2777                                         IGUIElement * element = getElementFromId(s.fid);
2778                                         gui::IGUICheckBox *e = NULL;
2779                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2780                                                 e = static_cast<gui::IGUICheckBox*>(element);
2781                                         }
2782
2783                                         if (e != 0) {
2784                                                 if (e->isChecked())
2785                                                         fields[name] = "true";
2786                                                 else
2787                                                         fields[name] = "false";
2788                                         }
2789                                 }
2790                                 else if (s.ftype == f_ScrollBar) {
2791                                         // no dynamic cast possible due to some distributions shipped
2792                                         // without rtti support in irrlicht
2793                                         IGUIElement * element = getElementFromId(s.fid);
2794                                         gui::IGUIScrollBar *e = NULL;
2795                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
2796                                                 e = static_cast<gui::IGUIScrollBar*>(element);
2797                                         }
2798
2799                                         if (e != 0) {
2800                                                 std::stringstream os;
2801                                                 os << e->getPos();
2802                                                 if (s.fdefault == L"Changed")
2803                                                         fields[name] = "CHG:" + os.str();
2804                                                 else
2805                                                         fields[name] = "VAL:" + os.str();
2806                                         }
2807                                 }
2808                                 else
2809                                 {
2810                                         IGUIElement* e = getElementFromId(s.fid);
2811                                         if(e != NULL) {
2812                                                 fields[name] = wide_to_utf8(e->getText());
2813                                         }
2814                                 }
2815                         }
2816                 }
2817
2818                 m_text_dst->gotText(fields);
2819         }
2820 }
2821
2822 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2823 {
2824         while(tocheck != NULL) {
2825                 if (tocheck == parent) {
2826                         return true;
2827                 }
2828                 tocheck = tocheck->getParent();
2829         }
2830         return false;
2831 }
2832
2833 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2834 {
2835         // The IGUITabControl renders visually using the skin's selected
2836         // font, which we override for the duration of form drawing,
2837         // but computes tab hotspots based on how it would have rendered
2838         // using the font that is selected at the time of button release.
2839         // To make these two consistent, temporarily override the skin's
2840         // font while the IGUITabControl is processing the event.
2841         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
2842                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2843                 s32 x = event.MouseInput.X;
2844                 s32 y = event.MouseInput.Y;
2845                 gui::IGUIElement *hovered =
2846                         Environment->getRootGUIElement()->getElementFromPoint(
2847                                 core::position2d<s32>(x, y));
2848                 if (hovered && isMyChild(hovered) &&
2849                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
2850                         gui::IGUISkin* skin = Environment->getSkin();
2851                         sanity_check(skin != NULL);
2852                         gui::IGUIFont *old_font = skin->getFont();
2853                         skin->setFont(m_font);
2854                         bool retval = hovered->OnEvent(event);
2855                         skin->setFont(old_font);
2856                         return retval;
2857                 }
2858         }
2859
2860         // Fix Esc/Return key being eaten by checkboxen and tables
2861         if(event.EventType==EET_KEY_INPUT_EVENT) {
2862                 KeyPress kp(event.KeyInput);
2863                 if (kp == EscapeKey || kp == CancelKey
2864                                 || kp == getKeySetting("keymap_inventory")
2865                                 || event.KeyInput.Key==KEY_RETURN) {
2866                         gui::IGUIElement *focused = Environment->getFocus();
2867                         if (focused && isMyChild(focused) &&
2868                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2869                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2870                                 OnEvent(event);
2871                                 return true;
2872                         }
2873                 }
2874         }
2875         // Mouse wheel events: send to hovered element instead of focused
2876         if(event.EventType==EET_MOUSE_INPUT_EVENT
2877                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
2878                 s32 x = event.MouseInput.X;
2879                 s32 y = event.MouseInput.Y;
2880                 gui::IGUIElement *hovered =
2881                         Environment->getRootGUIElement()->getElementFromPoint(
2882                                 core::position2d<s32>(x, y));
2883                 if (hovered && isMyChild(hovered)) {
2884                         hovered->OnEvent(event);
2885                         return true;
2886                 }
2887         }
2888
2889         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
2890                 s32 x = event.MouseInput.X;
2891                 s32 y = event.MouseInput.Y;
2892                 gui::IGUIElement *hovered =
2893                         Environment->getRootGUIElement()->getElementFromPoint(
2894                                 core::position2d<s32>(x, y));
2895                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2896                         m_old_tooltip_id = -1;
2897                         m_old_tooltip = L"";
2898                 }
2899                 if (!isChild(hovered,this)) {
2900                         if (DoubleClickDetection(event)) {
2901                                 return true;
2902                         }
2903                 }
2904         }
2905
2906         #ifdef __ANDROID__
2907         // display software keyboard when clicking edit boxes
2908         if (event.EventType == EET_MOUSE_INPUT_EVENT
2909                         && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2910                 gui::IGUIElement *hovered =
2911                         Environment->getRootGUIElement()->getElementFromPoint(
2912                                 core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
2913                 if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) {
2914                         bool retval = hovered->OnEvent(event);
2915                         if (retval) {
2916                                 Environment->setFocus(hovered);
2917                         }
2918                         m_JavaDialogFieldName = getNameByID(hovered->getID());
2919                         std::string message   = gettext("Enter ");
2920                         std::string label     = wide_to_utf8(getLabelByID(hovered->getID()));
2921                         if (label == "") {
2922                                 label = "text";
2923                         }
2924                         message += gettext(label) + ":";
2925
2926                         /* single line text input */
2927                         int type = 2;
2928
2929                         /* multi line text input */
2930                         if (((gui::IGUIEditBox*) hovered)->isMultiLineEnabled()) {
2931                                 type = 1;
2932                         }
2933
2934                         /* passwords are always single line */
2935                         if (((gui::IGUIEditBox*) hovered)->isPasswordBox()) {
2936                                 type = 3;
2937                         }
2938
2939                         porting::showInputDialog(gettext("ok"), "",
2940                                         wide_to_utf8(((gui::IGUIEditBox*) hovered)->getText()),
2941                                         type);
2942                         return retval;
2943                 }
2944         }
2945
2946         if (event.EventType == EET_TOUCH_INPUT_EVENT)
2947         {
2948                 SEvent translated;
2949                 memset(&translated, 0, sizeof(SEvent));
2950                 translated.EventType   = EET_MOUSE_INPUT_EVENT;
2951                 gui::IGUIElement* root = Environment->getRootGUIElement();
2952
2953                 if (!root) {
2954                         errorstream
2955                         << "GUIFormSpecMenu::preprocessEvent unable to get root element"
2956                         << std::endl;
2957                         return false;
2958                 }
2959                 gui::IGUIElement* hovered = root->getElementFromPoint(
2960                         core::position2d<s32>(
2961                                         event.TouchInput.X,
2962                                         event.TouchInput.Y));
2963
2964                 translated.MouseInput.X = event.TouchInput.X;
2965                 translated.MouseInput.Y = event.TouchInput.Y;
2966                 translated.MouseInput.Control = false;
2967
2968                 bool dont_send_event = false;
2969
2970                 if (event.TouchInput.touchedCount == 1) {
2971                         switch (event.TouchInput.Event) {
2972                                 case ETIE_PRESSED_DOWN:
2973                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2974                                         translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN;
2975                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2976                                         m_down_pos = m_pointer;
2977                                         break;
2978                                 case ETIE_MOVED:
2979                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2980                                         translated.MouseInput.Event = EMIE_MOUSE_MOVED;
2981                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2982                                         break;
2983                                 case ETIE_LEFT_UP:
2984                                         translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP;
2985                                         translated.MouseInput.ButtonStates = 0;
2986                                         hovered = root->getElementFromPoint(m_down_pos);
2987                                         /* we don't have a valid pointer element use last
2988                                          * known pointer pos */
2989                                         translated.MouseInput.X = m_pointer.X;
2990                                         translated.MouseInput.Y = m_pointer.Y;
2991
2992                                         /* reset down pos */
2993                                         m_down_pos = v2s32(0,0);
2994                                         break;
2995                                 default:
2996                                         dont_send_event = true;
2997                                         //this is not supposed to happen
2998                                         errorstream
2999                                         << "GUIFormSpecMenu::preprocessEvent unexpected usecase Event="
3000                                         << event.TouchInput.Event << std::endl;
3001                         }
3002                 } else if ( (event.TouchInput.touchedCount == 2) &&
3003                                 (event.TouchInput.Event == ETIE_PRESSED_DOWN) ) {
3004                         hovered = root->getElementFromPoint(m_down_pos);
3005
3006                         translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
3007                         translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT;
3008                         translated.MouseInput.X = m_pointer.X;
3009                         translated.MouseInput.Y = m_pointer.Y;
3010
3011                         if (hovered) {
3012                                 hovered->OnEvent(translated);
3013                         }
3014
3015                         translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP;
3016                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
3017
3018
3019                         if (hovered) {
3020                                 hovered->OnEvent(translated);
3021                         }
3022                         dont_send_event = true;
3023                 }
3024                 /* ignore unhandled 2 touch events ... accidental moving for example */
3025                 else if (event.TouchInput.touchedCount == 2) {
3026                         dont_send_event = true;
3027                 }
3028                 else if (event.TouchInput.touchedCount > 2) {
3029                         errorstream
3030                         << "GUIFormSpecMenu::preprocessEvent to many multitouch events "
3031                         << event.TouchInput.touchedCount << " ignoring them" << std::endl;
3032                 }
3033
3034                 if (dont_send_event) {
3035                         return true;
3036                 }
3037
3038                 /* check if translated event needs to be preprocessed again */
3039                 if (preprocessEvent(translated)) {
3040                         return true;
3041                 }
3042                 if (hovered) {
3043                         grab();
3044                         bool retval = hovered->OnEvent(translated);
3045
3046                         if (event.TouchInput.Event == ETIE_LEFT_UP) {
3047                                 /* reset pointer */
3048                                 m_pointer = v2s32(0,0);
3049                         }
3050                         drop();
3051                         return retval;
3052                 }
3053         }
3054         #endif
3055
3056         return false;
3057 }
3058
3059 /******************************************************************************/
3060 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3061 {
3062         /* The following code is for capturing double-clicks of the mouse button
3063          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3064          * -- which closes the form -- under some circumstances.
3065          *
3066          * There have been many github issues reporting this as a bug even though it
3067          * was an intended feature.  For this reason, remapping the double-click as
3068          * an ESC must be explicitly set when creating this class via the
3069          * /p remap_dbl_click parameter of the constructor.
3070          */
3071
3072         if (!m_remap_dbl_click)
3073                 return false;
3074
3075         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3076                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3077                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3078
3079                 m_doubleclickdetect[1].pos  = m_pointer;
3080                 m_doubleclickdetect[1].time = getTimeMs();
3081         }
3082         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3083                 u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs());
3084                 if (delta > 400) {
3085                         return false;
3086                 }
3087
3088                 double squaredistance =
3089                                 m_doubleclickdetect[0].pos
3090                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3091
3092                 if (squaredistance > (30*30)) {
3093                         return false;
3094                 }
3095
3096                 SEvent* translated = new SEvent();
3097                 assert(translated != 0);
3098                 //translate doubleclick to escape
3099                 memset(translated, 0, sizeof(SEvent));
3100                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3101                 translated->KeyInput.Key         = KEY_ESCAPE;
3102                 translated->KeyInput.Control     = false;
3103                 translated->KeyInput.Shift       = false;
3104                 translated->KeyInput.PressedDown = true;
3105                 translated->KeyInput.Char        = 0;
3106                 OnEvent(*translated);
3107
3108                 // no need to send the key up event as we're already deleted
3109                 // and no one else did notice this event
3110                 delete translated;
3111                 return true;
3112         }
3113
3114         return false;
3115 }
3116
3117 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3118 {
3119         if (event.EventType==EET_KEY_INPUT_EVENT) {
3120                 KeyPress kp(event.KeyInput);
3121                 if (event.KeyInput.PressedDown && ( (kp == EscapeKey) ||
3122                                 (kp == getKeySetting("keymap_inventory")) || (kp == CancelKey))) {
3123                         if (m_allowclose) {
3124                                 doPause = false;
3125                                 acceptInput(quit_mode_cancel);
3126                                 quitMenu();
3127                         } else {
3128                                 m_text_dst->gotText(L"MenuQuit");
3129                         }
3130                         return true;
3131                 } else if (m_client != NULL && event.KeyInput.PressedDown &&
3132                                 (kp == getKeySetting("keymap_screenshot"))) {
3133                         m_client->makeScreenshot(m_device);
3134                 }
3135                 if (event.KeyInput.PressedDown &&
3136                         (event.KeyInput.Key==KEY_RETURN ||
3137                          event.KeyInput.Key==KEY_UP ||
3138                          event.KeyInput.Key==KEY_DOWN)
3139                         ) {
3140                         switch (event.KeyInput.Key) {
3141                                 case KEY_RETURN:
3142                                         current_keys_pending.key_enter = true;
3143                                         break;
3144                                 case KEY_UP:
3145                                         current_keys_pending.key_up = true;
3146                                         break;
3147                                 case KEY_DOWN:
3148                                         current_keys_pending.key_down = true;
3149                                         break;
3150                                 break;
3151                                 default:
3152                                         //can't happen at all!
3153                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3154                                         break;
3155                         }
3156                         if (current_keys_pending.key_enter && m_allowclose) {
3157                                 acceptInput(quit_mode_accept);
3158                                 quitMenu();
3159                         } else {
3160                                 acceptInput();
3161                         }
3162                         return true;
3163                 }
3164
3165         }
3166
3167         /* Mouse event other than movement, or crossing the border of inventory
3168           field while holding right mouse button
3169          */
3170         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3171                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3172                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3173                           event.MouseInput.isRightPressed() &&
3174                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3175
3176                 // Get selected item and hovered/clicked item (s)
3177
3178                 m_old_tooltip_id = -1;
3179                 updateSelectedItem();
3180                 ItemSpec s = getItemAtPos(m_pointer);
3181
3182                 Inventory *inv_selected = NULL;
3183                 Inventory *inv_s = NULL;
3184                 InventoryList *list_s = NULL;
3185
3186                 if (m_selected_item) {
3187                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3188                         sanity_check(inv_selected);
3189                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3190                 }
3191
3192                 u32 s_count = 0;
3193
3194                 if (s.isValid())
3195                 do { // breakable
3196                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3197
3198                         if (!inv_s) {
3199                                 errorstream << "InventoryMenu: The selected inventory location "
3200                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3201                                                 << std::endl;
3202                                 s.i = -1;  // make it invalid again
3203                                 break;
3204                         }
3205
3206                         list_s = inv_s->getList(s.listname);
3207                         if (list_s == NULL) {
3208                                 verbosestream << "InventoryMenu: The selected inventory list \""
3209                                                 << s.listname << "\" does not exist" << std::endl;
3210                                 s.i = -1;  // make it invalid again
3211                                 break;
3212                         }
3213
3214                         if ((u32)s.i >= list_s->getSize()) {
3215                                 infostream << "InventoryMenu: The selected inventory list \""
3216                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
3217                                                 << list_s->getSize() << ")" << std::endl;
3218                                 s.i = -1;  // make it invalid again
3219                                 break;
3220                         }
3221
3222                         s_count = list_s->getItem(s.i).count;
3223                 } while(0);
3224
3225                 bool identical = (m_selected_item != NULL) && s.isValid() &&
3226                         (inv_selected == inv_s) &&
3227                         (m_selected_item->listname == s.listname) &&
3228                         (m_selected_item->i == s.i);
3229
3230                 // buttons: 0 = left, 1 = right, 2 = middle
3231                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event, -1 movement
3232                 int button = 0;
3233                 int updown = 2;
3234                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
3235                         { button = 0; updown = 0; }
3236                 else if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
3237                         { button = 1; updown = 0; }
3238                 else if (event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
3239                         { button = 2; updown = 0; }
3240                 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
3241                         { button = 0; updown = 1; }
3242                 else if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
3243                         { button = 1; updown = 1; }
3244                 else if (event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
3245                         { button = 2; updown = 1; }
3246                 else if (event.MouseInput.Event == EMIE_MOUSE_MOVED)
3247                         { updown = -1;}
3248
3249                 // Set this number to a positive value to generate a move action
3250                 // from m_selected_item to s.
3251                 u32 move_amount = 0;
3252
3253                 // Set this number to a positive value to generate a move action
3254                 // from s to the next inventory ring.
3255                 u32 shift_move_amount = 0;
3256
3257                 // Set this number to a positive value to generate a drop action
3258                 // from m_selected_item.
3259                 u32 drop_amount = 0;
3260
3261                 // Set this number to a positive value to generate a craft action at s.
3262                 u32 craft_amount = 0;
3263
3264                 if (updown == 0) {
3265                         // Some mouse button has been pressed
3266
3267                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3268                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3269
3270                         m_selected_dragging = false;
3271
3272                         if (s.isValid() && s.listname == "craftpreview") {
3273                                 // Craft preview has been clicked: craft
3274                                 craft_amount = (button == 2 ? 10 : 1);
3275                         } else if (m_selected_item == NULL) {
3276                                 if (s_count != 0) {
3277                                         // Non-empty stack has been clicked: select or shift-move it
3278                                         m_selected_item = new ItemSpec(s);
3279
3280                                         u32 count;
3281                                         if (button == 1)  // right
3282                                                 count = (s_count + 1) / 2;
3283                                         else if (button == 2)  // middle
3284                                                 count = MYMIN(s_count, 10);
3285                                         else  // left
3286                                                 count = s_count;
3287
3288                                         if (!event.MouseInput.Shift) {
3289                                                 // no shift: select item
3290                                                 m_selected_amount = count;
3291                                                 m_selected_dragging = true;
3292                                                 m_rmouse_auto_place = false;
3293                                         } else {
3294                                                 // shift pressed: move item
3295                                                 if (button != 1)
3296                                                         shift_move_amount = count;
3297                                                 else // count of 1 at left click like after drag & drop
3298                                                         shift_move_amount = 1;
3299                                         }
3300                                 }
3301                         } else { // m_selected_item != NULL
3302                                 assert(m_selected_amount >= 1);
3303
3304                                 if (s.isValid()) {
3305                                         // Clicked a slot: move
3306                                         if (button == 1)  // right
3307                                                 move_amount = 1;
3308                                         else if (button == 2)  // middle
3309                                                 move_amount = MYMIN(m_selected_amount, 10);
3310                                         else  // left
3311                                                 move_amount = m_selected_amount;
3312
3313                                         if (identical) {
3314                                                 if (move_amount >= m_selected_amount)
3315                                                         m_selected_amount = 0;
3316                                                 else
3317                                                         m_selected_amount -= move_amount;
3318                                                 move_amount = 0;
3319                                         }
3320                                 }
3321                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3322                                         // Clicked outside of the window: drop
3323                                         if (button == 1)  // right
3324                                                 drop_amount = 1;
3325                                         else if (button == 2)  // middle
3326                                                 drop_amount = MYMIN(m_selected_amount, 10);
3327                                         else  // left
3328                                                 drop_amount = m_selected_amount;
3329                                 }
3330                         }
3331                 }
3332                 else if (updown == 1) {
3333                         // Some mouse button has been released
3334
3335                         //infostream<<"Mouse button "<<button<<" released at p=("
3336                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3337
3338                         if (m_selected_item != NULL && m_selected_dragging && s.isValid()) {
3339                                 if (!identical) {
3340                                         // Dragged to different slot: move all selected
3341                                         move_amount = m_selected_amount;
3342                                 }
3343                         } else if (m_selected_item != NULL && m_selected_dragging &&
3344                                         !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
3345                                 // Dragged outside of window: drop all selected
3346                                 drop_amount = m_selected_amount;
3347                         }
3348
3349                         m_selected_dragging = false;
3350                         // Keep count of how many times right mouse button has been
3351                         // clicked. One click is drag without dropping. Click + release
3352                         // + click changes to drop one item when moved mode
3353                         if (button == 1 && m_selected_item != NULL)
3354                                 m_rmouse_auto_place = !m_rmouse_auto_place;
3355                 } else if (updown == -1) {
3356                         // Mouse has been moved and rmb is down and mouse pointer just
3357                         // entered a new inventory field (checked in the entry-if, this
3358                         // is the only action here that is generated by mouse movement)
3359                         if (m_selected_item != NULL && s.isValid()) {
3360                                 // Move 1 item
3361                                 // TODO: middle mouse to move 10 items might be handy
3362                                 if (m_rmouse_auto_place) {
3363                                         // Only move an item if the destination slot is empty
3364                                         // or contains the same item type as what is going to be
3365                                         // moved
3366                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3367                                         InventoryList *list_to = list_s;
3368                                         assert(list_from && list_to);
3369                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3370                                         ItemStack stack_to = list_to->getItem(s.i);
3371                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3372                                                 move_amount = 1;
3373                                 }
3374                         }
3375                 }
3376
3377                 // Possibly send inventory action to server
3378                 if (move_amount > 0) {
3379                         // Send IACTION_MOVE
3380
3381                         assert(m_selected_item && m_selected_item->isValid());
3382                         assert(s.isValid());
3383
3384                         assert(inv_selected && inv_s);
3385                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3386                         InventoryList *list_to = list_s;
3387                         assert(list_from && list_to);
3388                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3389                         ItemStack stack_to = list_to->getItem(s.i);
3390
3391                         // Check how many items can be moved
3392                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3393                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
3394                         // If source stack cannot be added to destination stack at all,
3395                         // they are swapped
3396                         if ((leftover.count == stack_from.count) &&
3397                                         (leftover.name == stack_from.name)) {
3398                                 m_selected_amount = stack_to.count;
3399                                 // In case the server doesn't directly swap them but instead
3400                                 // moves stack_to somewhere else, set this
3401                                 m_selected_content_guess = stack_to;
3402                                 m_selected_content_guess_inventory = s.inventoryloc;
3403                         }
3404                         // Source stack goes fully into destination stack
3405                         else if (leftover.empty()) {
3406                                 m_selected_amount -= move_amount;
3407                                 m_selected_content_guess = ItemStack(); // Clear
3408                         }
3409                         // Source stack goes partly into destination stack
3410                         else {
3411                                 move_amount -= leftover.count;
3412                                 m_selected_amount -= move_amount;
3413                                 m_selected_content_guess = ItemStack(); // Clear
3414                         }
3415
3416                         infostream << "Handing IACTION_MOVE to manager" << std::endl;
3417                         IMoveAction *a = new IMoveAction();
3418                         a->count = move_amount;
3419                         a->from_inv = m_selected_item->inventoryloc;
3420                         a->from_list = m_selected_item->listname;
3421                         a->from_i = m_selected_item->i;
3422                         a->to_inv = s.inventoryloc;
3423                         a->to_list = s.listname;
3424                         a->to_i = s.i;
3425                         m_invmgr->inventoryAction(a);
3426                 } else if (shift_move_amount > 0) {
3427                         u32 mis = m_inventory_rings.size();
3428                         u32 i = 0;
3429                         for (; i < mis; i++) {
3430                                 const ListRingSpec &sp = m_inventory_rings[i];
3431                                 if (sp.inventoryloc == s.inventoryloc
3432                                                 && sp.listname == s.listname)
3433                                         break;
3434                         }
3435                         do {
3436                                 if (i >= mis) // if not found
3437                                         break;
3438                                 u32 to_inv_ind = (i + 1) % mis;
3439                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
3440                                 InventoryList *list_from = list_s;
3441                                 if (!s.isValid())
3442                                         break;
3443                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
3444                                 if (!inv_to)
3445                                         break;
3446                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
3447                                 if (!list_to)
3448                                         break;
3449                                 ItemStack stack_from = list_from->getItem(s.i);
3450                                 assert(shift_move_amount <= stack_from.count);
3451                                 if (m_client->getProtoVersion() >= 25) {
3452                                         infostream << "Handing IACTION_MOVE to manager" << std::endl;
3453                                         IMoveAction *a = new IMoveAction();
3454                                         a->count = shift_move_amount;
3455                                         a->from_inv = s.inventoryloc;
3456                                         a->from_list = s.listname;
3457                                         a->from_i = s.i;
3458                                         a->to_inv = to_inv_sp.inventoryloc;
3459                                         a->to_list = to_inv_sp.listname;
3460                                         a->move_somewhere = true;
3461                                         m_invmgr->inventoryAction(a);
3462                                 } else {
3463                                         // find a place (or more than one) to add the new item
3464                                         u32 ilt_size = list_to->getSize();
3465                                         ItemStack leftover;
3466                                         for (u32 slot_to = 0; slot_to < ilt_size
3467                                                         && shift_move_amount > 0; slot_to++) {
3468                                                 list_to->itemFits(slot_to, stack_from, &leftover);
3469                                                 if (leftover.count < stack_from.count) {
3470                                                         infostream << "Handing IACTION_MOVE to manager" << std::endl;
3471                                                         IMoveAction *a = new IMoveAction();
3472                                                         a->count = MYMIN(shift_move_amount,
3473                                                                 (u32) (stack_from.count - leftover.count));
3474                                                         shift_move_amount -= a->count;
3475                                                         a->from_inv = s.inventoryloc;
3476                                                         a->from_list = s.listname;
3477                                                         a->from_i = s.i;
3478                                                         a->to_inv = to_inv_sp.inventoryloc;
3479                                                         a->to_list = to_inv_sp.listname;
3480                                                         a->to_i = slot_to;
3481                                                         m_invmgr->inventoryAction(a);
3482                                                         stack_from = leftover;
3483                                                 }
3484                                         }
3485                                 }
3486                         } while (0);
3487                 } else if (drop_amount > 0) {
3488                         m_selected_content_guess = ItemStack(); // Clear
3489
3490                         // Send IACTION_DROP
3491
3492                         assert(m_selected_item && m_selected_item->isValid());
3493                         assert(inv_selected);
3494                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3495                         assert(list_from);
3496                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3497
3498                         // Check how many items can be dropped
3499                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3500                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3501                         m_selected_amount -= drop_amount;
3502
3503                         infostream << "Handing IACTION_DROP to manager" << std::endl;
3504                         IDropAction *a = new IDropAction();
3505                         a->count = drop_amount;
3506                         a->from_inv = m_selected_item->inventoryloc;
3507                         a->from_list = m_selected_item->listname;
3508                         a->from_i = m_selected_item->i;
3509                         m_invmgr->inventoryAction(a);
3510                 } else if (craft_amount > 0) {
3511                         m_selected_content_guess = ItemStack(); // Clear
3512
3513                         // Send IACTION_CRAFT
3514
3515                         assert(s.isValid());
3516                         assert(inv_s);
3517
3518                         infostream << "Handing IACTION_CRAFT to manager" << std::endl;
3519                         ICraftAction *a = new ICraftAction();
3520                         a->count = craft_amount;
3521                         a->craft_inv = s.inventoryloc;
3522                         m_invmgr->inventoryAction(a);
3523                 }
3524
3525                 // If m_selected_amount has been decreased to zero, deselect
3526                 if (m_selected_amount == 0) {
3527                         delete m_selected_item;
3528                         m_selected_item = NULL;
3529                         m_selected_amount = 0;
3530                         m_selected_dragging = false;
3531                         m_selected_content_guess = ItemStack();
3532                 }
3533                 m_old_pointer = m_pointer;
3534         }
3535         if (event.EventType == EET_GUI_EVENT) {
3536
3537                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
3538                                 && isVisible()) {
3539                         // find the element that was clicked
3540                         for (unsigned int i=0; i<m_fields.size(); i++) {
3541                                 FieldSpec &s = m_fields[i];
3542                                 if ((s.ftype == f_TabHeader) &&
3543                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3544                                         s.send = true;
3545                                         acceptInput();
3546                                         s.send = false;
3547                                         return true;
3548                                 }
3549                         }
3550                 }
3551                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
3552                                 && isVisible()) {
3553                         if (!canTakeFocus(event.GUIEvent.Element)) {
3554                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
3555                                                 <<std::endl;
3556                                 // Returning true disables focus change
3557                                 return true;
3558                         }
3559                 }
3560                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
3561                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
3562                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
3563                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
3564                         unsigned int btn_id = event.GUIEvent.Caller->getID();
3565
3566                         if (btn_id == 257) {
3567                                 if (m_allowclose) {
3568                                         acceptInput(quit_mode_accept);
3569                                         quitMenu();
3570                                 } else {
3571                                         acceptInput();
3572                                         m_text_dst->gotText(L"ExitButton");
3573                                 }
3574                                 // quitMenu deallocates menu
3575                                 return true;
3576                         }
3577
3578                         // find the element that was clicked
3579                         for (u32 i = 0; i < m_fields.size(); i++) {
3580                                 FieldSpec &s = m_fields[i];
3581                                 // if its a button, set the send field so
3582                                 // lua knows which button was pressed
3583                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
3584                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3585                                         s.send = true;
3586                                         if (s.is_exit) {
3587                                                 if (m_allowclose) {
3588                                                         acceptInput(quit_mode_accept);
3589                                                         quitMenu();
3590                                                 } else {
3591                                                         m_text_dst->gotText(L"ExitButton");
3592                                                 }
3593                                                 return true;
3594                                         } else {
3595                                                 acceptInput(quit_mode_no);
3596                                                 s.send = false;
3597                                                 return true;
3598                                         }
3599                                 } else if ((s.ftype == f_DropDown) &&
3600                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3601                                         // only send the changed dropdown
3602                                         for (u32 i = 0; i < m_fields.size(); i++) {
3603                                                 FieldSpec &s2 = m_fields[i];
3604                                                 if (s2.ftype == f_DropDown) {
3605                                                         s2.send = false;
3606                                                 }
3607                                         }
3608                                         s.send = true;
3609                                         acceptInput(quit_mode_no);
3610
3611                                         // revert configuration to make sure dropdowns are sent on
3612                                         // regular button click
3613                                         for (u32 i = 0; i < m_fields.size(); i++) {
3614                                                 FieldSpec &s2 = m_fields[i];
3615                                                 if (s2.ftype == f_DropDown) {
3616                                                         s2.send = true;
3617                                                 }
3618                                         }
3619                                         return true;
3620                                 } else if ((s.ftype == f_ScrollBar) &&
3621                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3622                                         s.fdefault = L"Changed";
3623                                         acceptInput(quit_mode_no);
3624                                         s.fdefault = L"";
3625                                 }
3626                         }
3627                 }
3628
3629                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
3630                         if (event.GUIEvent.Caller->getID() > 257) {
3631
3632                                 if (m_allowclose) {
3633                                         acceptInput(quit_mode_accept);
3634                                         quitMenu();
3635                                 } else {
3636                                         current_keys_pending.key_enter = true;
3637                                         acceptInput();
3638                                 }
3639                                 // quitMenu deallocates menu
3640                                 return true;
3641                         }
3642                 }
3643
3644                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
3645                         int current_id = event.GUIEvent.Caller->getID();
3646                         if (current_id > 257) {
3647                                 // find the element that was clicked
3648                                 for (u32 i = 0; i < m_fields.size(); i++) {
3649                                         FieldSpec &s = m_fields[i];
3650                                         // if it's a table, set the send field
3651                                         // so lua knows which table was changed
3652                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
3653                                                 s.send = true;
3654                                                 acceptInput();
3655                                                 s.send=false;
3656                                         }
3657                                 }
3658                                 return true;
3659                         }
3660                 }
3661         }
3662
3663         return Parent ? Parent->OnEvent(event) : false;
3664 }
3665
3666 /**
3667  * get name of element by element id
3668  * @param id of element
3669  * @return name string or empty string
3670  */
3671 std::string GUIFormSpecMenu::getNameByID(s32 id)
3672 {
3673         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3674                                 iter != m_fields.end(); ++iter) {
3675                 if (iter->fid == id) {
3676                         return iter->fname;
3677                 }
3678         }
3679         return "";
3680 }
3681
3682 /**
3683  * get label of element by id
3684  * @param id of element
3685  * @return label string or empty string
3686  */
3687 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
3688 {
3689         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3690                                 iter != m_fields.end(); ++iter) {
3691                 if (iter->fid == id) {
3692                         return iter->flabel;
3693                 }
3694         }
3695         return L"";
3696 }