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