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