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