]> git.lizzy.rs Git - minetest.git/blob - src/guiFormSpecMenu.cpp
Exclude vertical mapblock borders when setting light
[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.5555 * 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                 target_font_height *= g_settings->getFloat("font_size")/TTF_DEFAULT_FONT_SIZE;
1995                 m_btn_height = use_imgsize*15.0/13 * 0.35;
1996
1997                 m_font = select_font_by_line_height(target_font_height);
1998
1999                 mydata.size = v2s32(
2000                         padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2001                         padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2002                 );
2003                 DesiredRect = mydata.rect = core::rect<s32>(
2004                                 mydata.screensize.X/2 - mydata.size.X/2 + offset.X,
2005                                 mydata.screensize.Y/2 - mydata.size.Y/2 + offset.Y,
2006                                 mydata.screensize.X/2 + mydata.size.X/2 + offset.X,
2007                                 mydata.screensize.Y/2 + mydata.size.Y/2 + offset.Y
2008                 );
2009         } else {
2010                 // Non-size[] form must consist only of text fields and
2011                 // implicit "Proceed" button.  Use default font, and
2012                 // temporary form size which will be recalculated below.
2013                 m_font = g_fontengine->getFont();
2014                 m_btn_height = font_line_height(m_font) * 0.875;
2015                 DesiredRect = core::rect<s32>(
2016                         mydata.screensize.X/2 - 580/2,
2017                         mydata.screensize.Y/2 - 300/2,
2018                         mydata.screensize.X/2 + 580/2,
2019                         mydata.screensize.Y/2 + 300/2
2020                 );
2021         }
2022         recalculateAbsolutePosition(false);
2023         mydata.basepos = getBasePos();
2024         m_tooltip_element->setOverrideFont(m_font);
2025
2026         gui::IGUISkin* skin = Environment->getSkin();
2027         assert(skin != NULL);
2028         gui::IGUIFont *old_font = skin->getFont();
2029         skin->setFont(m_font);
2030
2031         for (; i< elements.size(); i++) {
2032                 parseElement(&mydata, elements[i]);
2033         }
2034
2035         // If there are fields without explicit size[], add a "Proceed"
2036         // button and adjust size to fit all the fields.
2037         if (m_fields.size() && !mydata.explicit_size) {
2038                 mydata.rect = core::rect<s32>(
2039                                 mydata.screensize.X/2 - 580/2,
2040                                 mydata.screensize.Y/2 - 300/2,
2041                                 mydata.screensize.X/2 + 580/2,
2042                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
2043                 );
2044                 DesiredRect = mydata.rect;
2045                 recalculateAbsolutePosition(false);
2046                 mydata.basepos = getBasePos();
2047
2048                 {
2049                         v2s32 pos = mydata.basepos;
2050                         pos.Y = ((m_fields.size()+2)*60);
2051
2052                         v2s32 size = DesiredRect.getSize();
2053                         mydata.rect =
2054                                         core::rect<s32>(size.X/2-70, pos.Y,
2055                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2056                         wchar_t* text = wgettext("Proceed");
2057                         Environment->addButton(mydata.rect, this, 257, text);
2058                         delete[] text;
2059                 }
2060
2061         }
2062
2063         //set initial focus if parser didn't set it
2064         focused_element = Environment->getFocus();
2065         if (!focused_element
2066                         || !isMyChild(focused_element)
2067                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2068                 setInitialFocus();
2069
2070         skin->setFont(old_font);
2071 }
2072
2073 #ifdef __ANDROID__
2074 bool GUIFormSpecMenu::getAndroidUIInput()
2075 {
2076         /* no dialog shown */
2077         if (m_JavaDialogFieldName == L"") {
2078                 return false;
2079         }
2080
2081         /* still waiting */
2082         if (porting::getInputDialogState() == -1) {
2083                 return true;
2084         }
2085
2086         std::wstring fieldname = m_JavaDialogFieldName;
2087         m_JavaDialogFieldName = L"";
2088
2089         /* no value abort dialog processing */
2090         if (porting::getInputDialogState() != 0) {
2091                 return false;
2092         }
2093
2094         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2095                         iter != m_fields.end(); iter++) {
2096
2097                 if (iter->fname != fieldname) {
2098                         continue;
2099                 }
2100                 IGUIElement* tochange = getElementFromId(iter->fid);
2101
2102                 if (tochange == 0) {
2103                         return false;
2104                 }
2105
2106                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2107                         return false;
2108                 }
2109
2110                 std::string text = porting::getInputDialogValue();
2111
2112                 ((gui::IGUIEditBox*) tochange)->
2113                         setText(narrow_to_wide(text).c_str());
2114         }
2115         return false;
2116 }
2117 #endif
2118
2119 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2120 {
2121         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2122
2123         for(u32 i=0; i<m_inventorylists.size(); i++)
2124         {
2125                 const ListDrawSpec &s = m_inventorylists[i];
2126
2127                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2128                         s32 item_i = i + s.start_item_i;
2129                         s32 x = (i%s.geom.X) * spacing.X;
2130                         s32 y = (i/s.geom.X) * spacing.Y;
2131                         v2s32 p0(x,y);
2132                         core::rect<s32> rect = imgrect + s.pos + p0;
2133                         if(rect.isPointInside(p))
2134                         {
2135                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2136                         }
2137                 }
2138         }
2139
2140         return ItemSpec(InventoryLocation(), "", -1);
2141 }
2142
2143 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
2144 {
2145         video::IVideoDriver* driver = Environment->getVideoDriver();
2146
2147         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2148         if(!inv){
2149                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2150                                 <<"The inventory location "
2151                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2152                                 <<std::endl;
2153                 return;
2154         }
2155         InventoryList *ilist = inv->getList(s.listname);
2156         if(!ilist){
2157                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2158                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2159                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2160                                 <<std::endl;
2161                 return;
2162         }
2163
2164         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2165
2166         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
2167         {
2168                 s32 item_i = i + s.start_item_i;
2169                 if(item_i >= (s32) ilist->getSize())
2170                         break;
2171                 s32 x = (i%s.geom.X) * spacing.X;
2172                 s32 y = (i/s.geom.X) * spacing.Y;
2173                 v2s32 p(x,y);
2174                 core::rect<s32> rect = imgrect + s.pos + p;
2175                 ItemStack item;
2176                 if(ilist)
2177                         item = ilist->getItem(item_i);
2178
2179                 bool selected = m_selected_item
2180                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2181                         && m_selected_item->listname == s.listname
2182                         && m_selected_item->i == item_i;
2183                 bool hovering = rect.isPointInside(m_pointer);
2184
2185                 if(phase == 0)
2186                 {
2187                         if(hovering)
2188                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2189                         else
2190                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2191                 }
2192
2193                 //Draw inv slot borders
2194                 if (m_slotborder) {
2195                         s32 x1 = rect.UpperLeftCorner.X;
2196                         s32 y1 = rect.UpperLeftCorner.Y;
2197                         s32 x2 = rect.LowerRightCorner.X;
2198                         s32 y2 = rect.LowerRightCorner.Y;
2199                         s32 border = 1;
2200                         driver->draw2DRectangle(m_slotbordercolor,
2201                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2202                                                                 v2s32(x2 + border, y1)), NULL);
2203                         driver->draw2DRectangle(m_slotbordercolor,
2204                                 core::rect<s32>(v2s32(x1 - border, y2),
2205                                                                 v2s32(x2 + border, y2 + border)), NULL);
2206                         driver->draw2DRectangle(m_slotbordercolor,
2207                                 core::rect<s32>(v2s32(x1 - border, y1),
2208                                                                 v2s32(x1, y2)), NULL);
2209                         driver->draw2DRectangle(m_slotbordercolor,
2210                                 core::rect<s32>(v2s32(x2, y1),
2211                                                                 v2s32(x2 + border, y2)), NULL);
2212                 }
2213
2214                 if(phase == 1)
2215                 {
2216                         // Draw item stack
2217                         if(selected)
2218                         {
2219                                 item.takeItem(m_selected_amount);
2220                         }
2221                         if(!item.empty())
2222                         {
2223                                 drawItemStack(driver, m_font, item,
2224                                                 rect, &AbsoluteClippingRect, m_gamedef);
2225                         }
2226
2227                         // Draw tooltip
2228                         std::string tooltip_text = "";
2229                         if (hovering && !m_selected_item)
2230                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
2231                         if (tooltip_text != "") {
2232                                 std::vector<std::string> tt_rows = str_split(tooltip_text, '\n');
2233                                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2234                                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2235                                 m_tooltip_element->setVisible(true);
2236                                 this->bringToFront(m_tooltip_element);
2237                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
2238                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2239                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2240                                 v2u32 screenSize = driver->getScreenSize();
2241                                 int tooltip_offset_x = m_btn_height;
2242                                 int tooltip_offset_y = m_btn_height;
2243 #ifdef __ANDROID__
2244                                 tooltip_offset_x *= 3;
2245                                 tooltip_offset_y  = 0;
2246                                 if (m_pointer.X > (s32)screenSize.X / 2)
2247                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2248 #endif
2249                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2250                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2251                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2252                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2253                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2254                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2255                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2256                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2257                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2258                         }
2259                 }
2260         }
2261 }
2262
2263 void GUIFormSpecMenu::drawSelectedItem()
2264 {
2265         if(!m_selected_item)
2266                 return;
2267
2268         video::IVideoDriver* driver = Environment->getVideoDriver();
2269
2270         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2271         assert(inv);
2272         InventoryList *list = inv->getList(m_selected_item->listname);
2273         assert(list);
2274         ItemStack stack = list->getItem(m_selected_item->i);
2275         stack.count = m_selected_amount;
2276
2277         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2278         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2279         drawItemStack(driver, m_font, stack, rect, NULL, m_gamedef);
2280 }
2281
2282 void GUIFormSpecMenu::drawMenu()
2283 {
2284         if(m_form_src){
2285                 std::string newform = m_form_src->getForm();
2286                 if(newform != m_formspec_string){
2287                         m_formspec_string = newform;
2288                         regenerateGui(m_screensize_old);
2289                 }
2290         }
2291
2292         gui::IGUISkin* skin = Environment->getSkin();
2293         assert(skin != NULL);
2294         gui::IGUIFont *old_font = skin->getFont();
2295         skin->setFont(m_font);
2296
2297         updateSelectedItem();
2298
2299         video::IVideoDriver* driver = Environment->getVideoDriver();
2300
2301         v2u32 screenSize = driver->getScreenSize();
2302         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
2303         if (m_bgfullscreen)
2304                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
2305         else
2306                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2307
2308         m_tooltip_element->setVisible(false);
2309
2310         /*
2311                 Draw backgrounds
2312         */
2313         for(u32 i=0; i<m_backgrounds.size(); i++)
2314         {
2315                 const ImageDrawSpec &spec = m_backgrounds[i];
2316                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2317
2318                 if (texture != 0) {
2319                         // Image size on screen
2320                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2321                         // Image rectangle on screen
2322                         core::rect<s32> rect = imgrect + spec.pos;
2323
2324                         if (m_clipbackground) {
2325                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2326                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2327                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2328                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2329                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2330                         }
2331
2332                         const video::SColor color(255,255,255,255);
2333                         const video::SColor colors[] = {color,color,color,color};
2334                         driver->draw2DImage(texture, rect,
2335                                 core::rect<s32>(core::position2d<s32>(0,0),
2336                                                 core::dimension2di(texture->getOriginalSize())),
2337                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2338                 }
2339                 else {
2340                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2341                         errorstream << "\t" << spec.name << std::endl;
2342                 }
2343         }
2344
2345         /*
2346                 Draw Boxes
2347         */
2348         for(u32 i=0; i<m_boxes.size(); i++)
2349         {
2350                 const BoxDrawSpec &spec = m_boxes[i];
2351
2352                 irr::video::SColor todraw = spec.color;
2353
2354                 todraw.setAlpha(140);
2355
2356                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2357                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2358
2359                 driver->draw2DRectangle(todraw, rect, 0);
2360         }
2361         /*
2362                 Draw images
2363         */
2364         for(u32 i=0; i<m_images.size(); i++)
2365         {
2366                 const ImageDrawSpec &spec = m_images[i];
2367                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2368
2369                 if (texture != 0) {
2370                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2371                         // Image size on screen
2372                         core::rect<s32> imgrect;
2373
2374                         if (spec.scale)
2375                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2376                         else {
2377
2378                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2379                         }
2380                         // Image rectangle on screen
2381                         core::rect<s32> rect = imgrect + spec.pos;
2382                         const video::SColor color(255,255,255,255);
2383                         const video::SColor colors[] = {color,color,color,color};
2384                         driver->draw2DImage(texture, rect,
2385                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2386                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2387                 }
2388                 else {
2389                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2390                         errorstream << "\t" << spec.name << std::endl;
2391                 }
2392         }
2393
2394         /*
2395                 Draw item images
2396         */
2397         for(u32 i=0; i<m_itemimages.size(); i++)
2398         {
2399                 if (m_gamedef == 0)
2400                         break;
2401
2402                 const ImageDrawSpec &spec = m_itemimages[i];
2403                 IItemDefManager *idef = m_gamedef->idef();
2404                 ItemStack item;
2405                 item.deSerialize(spec.name, idef);
2406                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
2407                 // Image size on screen
2408                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2409                 // Image rectangle on screen
2410                 core::rect<s32> rect = imgrect + spec.pos;
2411                 const video::SColor color(255,255,255,255);
2412                 const video::SColor colors[] = {color,color,color,color};
2413                 driver->draw2DImage(texture, rect,
2414                         core::rect<s32>(core::position2d<s32>(0,0),
2415                                         core::dimension2di(texture->getOriginalSize())),
2416                         NULL/*&AbsoluteClippingRect*/, colors, true);
2417         }
2418
2419         /*
2420                 Draw items
2421                 Phase 0: Item slot rectangles
2422                 Phase 1: Item images; prepare tooltip
2423         */
2424         int start_phase=0;
2425         for(int phase=start_phase; phase<=1; phase++)
2426         for(u32 i=0; i<m_inventorylists.size(); i++)
2427         {
2428                 drawList(m_inventorylists[i], phase);
2429         }
2430
2431         /*
2432                 Call base class
2433         */
2434         gui::IGUIElement::draw();
2435
2436 /* TODO find way to show tooltips on touchscreen */
2437 #ifndef HAVE_TOUCHSCREENGUI
2438         m_pointer = m_device->getCursorControl()->getPosition();
2439 #endif
2440
2441         /*
2442                 Draw fields/buttons tooltips
2443         */
2444         gui::IGUIElement *hovered =
2445                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2446
2447         if (hovered != NULL) {
2448                 s32 id = hovered->getID();
2449
2450                 u32 delta = 0;
2451                 if (id == -1) {
2452                         m_old_tooltip_id = id;
2453                         m_old_tooltip = "";
2454                 } else {
2455                         if (id == m_old_tooltip_id) {
2456                                 delta = porting::getDeltaMs(m_hovered_time, getTimeMs());
2457                         } else {
2458                                 m_hovered_time = getTimeMs();
2459                                 m_old_tooltip_id = id;
2460                         }
2461                 }
2462
2463                 if (id != -1 && delta >= m_tooltip_show_delay) {
2464                         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2465                                         iter != m_fields.end(); iter++) {
2466                                 if ( (iter->fid == id) && (m_tooltips[iter->fname].tooltip != "") ){
2467                                         if (m_old_tooltip != m_tooltips[iter->fname].tooltip) {
2468                                                 m_old_tooltip = m_tooltips[iter->fname].tooltip;
2469                                                 m_tooltip_element->setText(narrow_to_wide(m_tooltips[iter->fname].tooltip).c_str());
2470                                                 std::vector<std::string> tt_rows = str_split(m_tooltips[iter->fname].tooltip, '\n');
2471                                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2472                                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2473                                                 int tooltip_offset_x = m_btn_height;
2474                                                 int tooltip_offset_y = m_btn_height;
2475 #ifdef __ANDROID__
2476                                                 tooltip_offset_x *= 3;
2477                                                 tooltip_offset_y  = 0;
2478                                                 if (m_pointer.X > (s32)screenSize.X / 2)
2479                                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2480 #endif
2481                                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2482                                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2483                                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2484                                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2485                                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2486                                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2487                                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2488                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2489                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2490                                         }
2491                                         m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor);
2492                                         m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color);
2493                                         m_tooltip_element->setVisible(true);
2494                                         this->bringToFront(m_tooltip_element);
2495                                         break;
2496                                 }
2497                         }
2498                 }
2499         }
2500
2501         /*
2502                 Draw dragged item stack
2503         */
2504         drawSelectedItem();
2505
2506         skin->setFont(old_font);
2507 }
2508
2509 void GUIFormSpecMenu::updateSelectedItem()
2510 {
2511         // If the selected stack has become empty for some reason, deselect it.
2512         // If the selected stack has become inaccessible, deselect it.
2513         // If the selected stack has become smaller, adjust m_selected_amount.
2514         ItemStack selected = verifySelectedItem();
2515
2516         // WARNING: BLACK MAGIC
2517         // See if there is a stack suited for our current guess.
2518         // If such stack does not exist, clear the guess.
2519         if(m_selected_content_guess.name != "" &&
2520                         selected.name == m_selected_content_guess.name &&
2521                         selected.count == m_selected_content_guess.count){
2522                 // Selected item fits the guess. Skip the black magic.
2523         }
2524         else if(m_selected_content_guess.name != ""){
2525                 bool found = false;
2526                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2527                         const ListDrawSpec &s = m_inventorylists[i];
2528                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2529                         if(!inv)
2530                                 continue;
2531                         InventoryList *list = inv->getList(s.listname);
2532                         if(!list)
2533                                 continue;
2534                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2535                                 u32 item_i = i + s.start_item_i;
2536                                 if(item_i >= list->getSize())
2537                                         continue;
2538                                 ItemStack stack = list->getItem(item_i);
2539                                 if(stack.name == m_selected_content_guess.name &&
2540                                                 stack.count == m_selected_content_guess.count){
2541                                         found = true;
2542                                         infostream<<"Client: Changing selected content guess to "
2543                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2544                                                         <<" "<<item_i<<std::endl;
2545                                         delete m_selected_item;
2546                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2547                                         m_selected_amount = stack.count;
2548                                 }
2549                         }
2550                 }
2551                 if(!found){
2552                         infostream<<"Client: Discarding selected content guess: "
2553                                         <<m_selected_content_guess.getItemString()<<std::endl;
2554                         m_selected_content_guess.name = "";
2555                 }
2556         }
2557
2558         // If craftresult is nonempty and nothing else is selected, select it now.
2559         if(!m_selected_item)
2560         {
2561                 for(u32 i=0; i<m_inventorylists.size(); i++)
2562                 {
2563                         const ListDrawSpec &s = m_inventorylists[i];
2564                         if(s.listname == "craftpreview")
2565                         {
2566                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2567                                 InventoryList *list = inv->getList("craftresult");
2568                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2569                                 {
2570                                         m_selected_item = new ItemSpec;
2571                                         m_selected_item->inventoryloc = s.inventoryloc;
2572                                         m_selected_item->listname = "craftresult";
2573                                         m_selected_item->i = 0;
2574                                         m_selected_amount = 0;
2575                                         m_selected_dragging = false;
2576                                         break;
2577                                 }
2578                         }
2579                 }
2580         }
2581
2582         // If craftresult is selected, keep the whole stack selected
2583         if(m_selected_item && m_selected_item->listname == "craftresult")
2584         {
2585                 m_selected_amount = verifySelectedItem().count;
2586         }
2587 }
2588
2589 ItemStack GUIFormSpecMenu::verifySelectedItem()
2590 {
2591         // If the selected stack has become empty for some reason, deselect it.
2592         // If the selected stack has become inaccessible, deselect it.
2593         // If the selected stack has become smaller, adjust m_selected_amount.
2594         // Return the selected stack.
2595
2596         if(m_selected_item)
2597         {
2598                 if(m_selected_item->isValid())
2599                 {
2600                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2601                         if(inv)
2602                         {
2603                                 InventoryList *list = inv->getList(m_selected_item->listname);
2604                                 if(list && (u32) m_selected_item->i < list->getSize())
2605                                 {
2606                                         ItemStack stack = list->getItem(m_selected_item->i);
2607                                         if(m_selected_amount > stack.count)
2608                                                 m_selected_amount = stack.count;
2609                                         if(!stack.empty())
2610                                                 return stack;
2611                                 }
2612                         }
2613                 }
2614
2615                 // selection was not valid
2616                 delete m_selected_item;
2617                 m_selected_item = NULL;
2618                 m_selected_amount = 0;
2619                 m_selected_dragging = false;
2620         }
2621         return ItemStack();
2622 }
2623
2624 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2625 {
2626         if(m_text_dst)
2627         {
2628                 std::map<std::string, std::string> fields;
2629
2630                 if (quitmode == quit_mode_accept) {
2631                         fields["quit"] = "true";
2632                 }
2633
2634                 if (quitmode == quit_mode_cancel) {
2635                         fields["quit"] = "true";
2636                         m_text_dst->gotText(fields);
2637                         return;
2638                 }
2639
2640                 if (current_keys_pending.key_down) {
2641                         fields["key_down"] = "true";
2642                         current_keys_pending.key_down = false;
2643                 }
2644
2645                 if (current_keys_pending.key_up) {
2646                         fields["key_up"] = "true";
2647                         current_keys_pending.key_up = false;
2648                 }
2649
2650                 if (current_keys_pending.key_enter) {
2651                         fields["key_enter"] = "true";
2652                         current_keys_pending.key_enter = false;
2653                 }
2654
2655                 if (current_keys_pending.key_escape) {
2656                         fields["key_escape"] = "true";
2657                         current_keys_pending.key_escape = false;
2658                 }
2659
2660                 for(unsigned int i=0; i<m_fields.size(); i++) {
2661                         const FieldSpec &s = m_fields[i];
2662                         if(s.send) {
2663                                 std::string name  = wide_to_narrow(s.fname);
2664                                 if(s.ftype == f_Button) {
2665                                         fields[name] = wide_to_narrow(s.flabel);
2666                                 }
2667                                 else if(s.ftype == f_Table) {
2668                                         GUITable *table = getTable(s.fname);
2669                                         if (table) {
2670                                                 fields[name] = table->checkEvent();
2671                                         }
2672                                 }
2673                                 else if(s.ftype == f_DropDown) {
2674                                         // no dynamic cast possible due to some distributions shipped
2675                                         // without rtti support in irrlicht
2676                                         IGUIElement * element = getElementFromId(s.fid);
2677                                         gui::IGUIComboBox *e = NULL;
2678                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2679                                                 e = static_cast<gui::IGUIComboBox*>(element);
2680                                         }
2681                                         s32 selected = e->getSelected();
2682                                         if (selected >= 0) {
2683                                                 fields[name] =
2684                                                         wide_to_narrow(e->getItem(selected));
2685                                         }
2686                                 }
2687                                 else if (s.ftype == f_TabHeader) {
2688                                         // no dynamic cast possible due to some distributions shipped
2689                                         // without rtti support in irrlicht
2690                                         IGUIElement * element = getElementFromId(s.fid);
2691                                         gui::IGUITabControl *e = NULL;
2692                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2693                                                 e = static_cast<gui::IGUITabControl*>(element);
2694                                         }
2695
2696                                         if (e != 0) {
2697                                                 std::stringstream ss;
2698                                                 ss << (e->getActiveTab() +1);
2699                                                 fields[name] = ss.str();
2700                                         }
2701                                 }
2702                                 else if (s.ftype == f_CheckBox) {
2703                                         // no dynamic cast possible due to some distributions shipped
2704                                         // without rtti support in irrlicht
2705                                         IGUIElement * element = getElementFromId(s.fid);
2706                                         gui::IGUICheckBox *e = NULL;
2707                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2708                                                 e = static_cast<gui::IGUICheckBox*>(element);
2709                                         }
2710
2711                                         if (e != 0) {
2712                                                 if (e->isChecked())
2713                                                         fields[name] = "true";
2714                                                 else
2715                                                         fields[name] = "false";
2716                                         }
2717                                 }
2718                                 else if (s.ftype == f_ScrollBar) {
2719                                         // no dynamic cast possible due to some distributions shipped
2720                                         // without rtti support in irrlicht
2721                                         IGUIElement * element = getElementFromId(s.fid);
2722                                         gui::IGUIScrollBar *e = NULL;
2723                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
2724                                                 e = static_cast<gui::IGUIScrollBar*>(element);
2725                                         }
2726
2727                                         if (e != 0) {
2728                                                 std::stringstream os;
2729                                                 os << e->getPos();
2730                                                 if (s.fdefault == L"Changed")
2731                                                         fields[name] = "CHG:" + os.str();
2732                                                 else
2733                                                         fields[name] = "VAL:" + os.str();
2734                                         }
2735                                 }
2736                                 else
2737                                 {
2738                                         IGUIElement* e = getElementFromId(s.fid);
2739                                         if(e != NULL) {
2740                                                 fields[name] = wide_to_narrow(e->getText());
2741                                         }
2742                                 }
2743                         }
2744                 }
2745
2746                 m_text_dst->gotText(fields);
2747         }
2748 }
2749
2750 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2751 {
2752         while(tocheck != NULL) {
2753                 if (tocheck == parent) {
2754                         return true;
2755                 }
2756                 tocheck = tocheck->getParent();
2757         }
2758         return false;
2759 }
2760
2761 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2762 {
2763         // The IGUITabControl renders visually using the skin's selected
2764         // font, which we override for the duration of form drawing,
2765         // but computes tab hotspots based on how it would have rendered
2766         // using the font that is selected at the time of button release.
2767         // To make these two consistent, temporarily override the skin's
2768         // font while the IGUITabControl is processing the event.
2769         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
2770                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2771                 s32 x = event.MouseInput.X;
2772                 s32 y = event.MouseInput.Y;
2773                 gui::IGUIElement *hovered =
2774                         Environment->getRootGUIElement()->getElementFromPoint(
2775                                 core::position2d<s32>(x, y));
2776                 if (hovered && isMyChild(hovered) &&
2777                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
2778                         gui::IGUISkin* skin = Environment->getSkin();
2779                         assert(skin != NULL);
2780                         gui::IGUIFont *old_font = skin->getFont();
2781                         skin->setFont(m_font);
2782                         bool retval = hovered->OnEvent(event);
2783                         skin->setFont(old_font);
2784                         return retval;
2785                 }
2786         }
2787
2788         // Fix Esc/Return key being eaten by checkboxen and tables
2789         if(event.EventType==EET_KEY_INPUT_EVENT) {
2790                 KeyPress kp(event.KeyInput);
2791                 if (kp == EscapeKey || kp == CancelKey
2792                                 || kp == getKeySetting("keymap_inventory")
2793                                 || event.KeyInput.Key==KEY_RETURN) {
2794                         gui::IGUIElement *focused = Environment->getFocus();
2795                         if (focused && isMyChild(focused) &&
2796                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2797                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2798                                 OnEvent(event);
2799                                 return true;
2800                         }
2801                 }
2802         }
2803         // Mouse wheel events: send to hovered element instead of focused
2804         if(event.EventType==EET_MOUSE_INPUT_EVENT
2805                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
2806                 s32 x = event.MouseInput.X;
2807                 s32 y = event.MouseInput.Y;
2808                 gui::IGUIElement *hovered =
2809                         Environment->getRootGUIElement()->getElementFromPoint(
2810                                 core::position2d<s32>(x, y));
2811                 if (hovered && isMyChild(hovered)) {
2812                         hovered->OnEvent(event);
2813                         return true;
2814                 }
2815         }
2816
2817         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
2818                 s32 x = event.MouseInput.X;
2819                 s32 y = event.MouseInput.Y;
2820                 gui::IGUIElement *hovered =
2821                         Environment->getRootGUIElement()->getElementFromPoint(
2822                                 core::position2d<s32>(x, y));
2823                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2824                         m_old_tooltip_id = -1;
2825                         m_old_tooltip = "";
2826                 }
2827                 if (!isChild(hovered,this)) {
2828                         if (DoubleClickDetection(event)) {
2829                                 return true;
2830                         }
2831                 }
2832         }
2833
2834         #ifdef __ANDROID__
2835         // display software keyboard when clicking edit boxes
2836         if (event.EventType == EET_MOUSE_INPUT_EVENT
2837                         && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2838                 gui::IGUIElement *hovered =
2839                         Environment->getRootGUIElement()->getElementFromPoint(
2840                                 core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
2841                 if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) {
2842                         bool retval = hovered->OnEvent(event);
2843                         if (retval) {
2844                                 Environment->setFocus(hovered);
2845                         }
2846                         m_JavaDialogFieldName = getNameByID(hovered->getID());
2847                         std::string message   = gettext("Enter ");
2848                         std::string label     = wide_to_narrow(getLabelByID(hovered->getID()));
2849                         if (label == "") {
2850                                 label = "text";
2851                         }
2852                         message += gettext(label) + ":";
2853
2854                         /* single line text input */
2855                         int type = 2;
2856
2857                         /* multi line text input */
2858                         if (((gui::IGUIEditBox*) hovered)->isMultiLineEnabled()) {
2859                                 type = 1;
2860                         }
2861
2862                         /* passwords are always single line */
2863                         if (((gui::IGUIEditBox*) hovered)->isPasswordBox()) {
2864                                 type = 3;
2865                         }
2866
2867                         porting::showInputDialog(gettext("ok"), "",
2868                                         wide_to_narrow(((gui::IGUIEditBox*) hovered)->getText()),
2869                                         type);
2870                         return retval;
2871                 }
2872         }
2873
2874         if (event.EventType == EET_TOUCH_INPUT_EVENT)
2875         {
2876                 SEvent translated;
2877                 memset(&translated, 0, sizeof(SEvent));
2878                 translated.EventType   = EET_MOUSE_INPUT_EVENT;
2879                 gui::IGUIElement* root = Environment->getRootGUIElement();
2880
2881                 if (!root) {
2882                         errorstream
2883                         << "GUIFormSpecMenu::preprocessEvent unable to get root element"
2884                         << std::endl;
2885                         return false;
2886                 }
2887                 gui::IGUIElement* hovered = root->getElementFromPoint(
2888                         core::position2d<s32>(
2889                                         event.TouchInput.X,
2890                                         event.TouchInput.Y));
2891
2892                 translated.MouseInput.X = event.TouchInput.X;
2893                 translated.MouseInput.Y = event.TouchInput.Y;
2894                 translated.MouseInput.Control = false;
2895
2896                 bool dont_send_event = false;
2897
2898                 if (event.TouchInput.touchedCount == 1) {
2899                         switch (event.TouchInput.Event) {
2900                                 case ETIE_PRESSED_DOWN:
2901                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2902                                         translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN;
2903                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2904                                         m_down_pos = m_pointer;
2905                                         break;
2906                                 case ETIE_MOVED:
2907                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2908                                         translated.MouseInput.Event = EMIE_MOUSE_MOVED;
2909                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2910                                         break;
2911                                 case ETIE_LEFT_UP:
2912                                         translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP;
2913                                         translated.MouseInput.ButtonStates = 0;
2914                                         hovered = root->getElementFromPoint(m_down_pos);
2915                                         /* we don't have a valid pointer element use last
2916                                          * known pointer pos */
2917                                         translated.MouseInput.X = m_pointer.X;
2918                                         translated.MouseInput.Y = m_pointer.Y;
2919
2920                                         /* reset down pos */
2921                                         m_down_pos = v2s32(0,0);
2922                                         break;
2923                                 default:
2924                                         dont_send_event = true;
2925                                         //this is not supposed to happen
2926                                         errorstream
2927                                         << "GUIFormSpecMenu::preprocessEvent unexpected usecase Event="
2928                                         << event.TouchInput.Event << std::endl;
2929                         }
2930                 } else if ( (event.TouchInput.touchedCount == 2) &&
2931                                 (event.TouchInput.Event == ETIE_PRESSED_DOWN) ) {
2932                         hovered = root->getElementFromPoint(m_down_pos);
2933
2934                         translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
2935                         translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT;
2936                         translated.MouseInput.X = m_pointer.X;
2937                         translated.MouseInput.Y = m_pointer.Y;
2938
2939                         if (hovered) {
2940                                 hovered->OnEvent(translated);
2941                         }
2942
2943                         translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP;
2944                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2945
2946
2947                         if (hovered) {
2948                                 hovered->OnEvent(translated);
2949                         }
2950                         dont_send_event = true;
2951                 }
2952                 /* ignore unhandled 2 touch events ... accidental moving for example */
2953                 else if (event.TouchInput.touchedCount == 2) {
2954                         dont_send_event = true;
2955                 }
2956                 else if (event.TouchInput.touchedCount > 2) {
2957                         errorstream
2958                         << "GUIFormSpecMenu::preprocessEvent to many multitouch events "
2959                         << event.TouchInput.touchedCount << " ignoring them" << std::endl;
2960                 }
2961
2962                 if (dont_send_event) {
2963                         return true;
2964                 }
2965
2966                 /* check if translated event needs to be preprocessed again */
2967                 if (preprocessEvent(translated)) {
2968                         return true;
2969                 }
2970                 if (hovered) {
2971                         grab();
2972                         bool retval = hovered->OnEvent(translated);
2973
2974                         if (event.TouchInput.Event == ETIE_LEFT_UP) {
2975                                 /* reset pointer */
2976                                 m_pointer = v2s32(0,0);
2977                         }
2978                         drop();
2979                         return retval;
2980                 }
2981         }
2982         #endif
2983
2984         return false;
2985 }
2986
2987 /******************************************************************************/
2988 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
2989 {
2990         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2991                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
2992                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
2993
2994                 m_doubleclickdetect[1].pos  = m_pointer;
2995                 m_doubleclickdetect[1].time = getTimeMs();
2996         }
2997         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2998                 u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs());
2999                 if (delta > 400) {
3000                         return false;
3001                 }
3002
3003                 double squaredistance =
3004                                 m_doubleclickdetect[0].pos
3005                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3006
3007                 if (squaredistance > (30*30)) {
3008                         return false;
3009                 }
3010
3011                 SEvent* translated = new SEvent();
3012                 assert(translated != 0);
3013                 //translate doubleclick to escape
3014                 memset(translated, 0, sizeof(SEvent));
3015                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3016                 translated->KeyInput.Key         = KEY_ESCAPE;
3017                 translated->KeyInput.Control     = false;
3018                 translated->KeyInput.Shift       = false;
3019                 translated->KeyInput.PressedDown = true;
3020                 translated->KeyInput.Char        = 0;
3021                 OnEvent(*translated);
3022
3023                 // no need to send the key up event as we're already deleted
3024                 // and no one else did notice this event
3025                 delete translated;
3026                 return true;
3027         }
3028         return false;
3029 }
3030
3031 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3032 {
3033         if(event.EventType==EET_KEY_INPUT_EVENT) {
3034                 KeyPress kp(event.KeyInput);
3035                 if (event.KeyInput.PressedDown && ( (kp == EscapeKey) ||
3036                         (kp == getKeySetting("keymap_inventory")) || (kp == CancelKey))) {
3037                         if (m_allowclose) {
3038                                 doPause = false;
3039                                 acceptInput(quit_mode_cancel);
3040                                 quitMenu();
3041                         } else {
3042                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
3043                         }
3044                         return true;
3045                 } else if (m_client != NULL && event.KeyInput.PressedDown &&
3046                         (kp == getKeySetting("keymap_screenshot"))) {
3047                                 m_client->makeScreenshot(m_device);
3048                 }
3049                 if (event.KeyInput.PressedDown &&
3050                         (event.KeyInput.Key==KEY_RETURN ||
3051                          event.KeyInput.Key==KEY_UP ||
3052                          event.KeyInput.Key==KEY_DOWN)
3053                         ) {
3054                         switch (event.KeyInput.Key) {
3055                                 case KEY_RETURN:
3056                                         current_keys_pending.key_enter = true;
3057                                         break;
3058                                 case KEY_UP:
3059                                         current_keys_pending.key_up = true;
3060                                         break;
3061                                 case KEY_DOWN:
3062                                         current_keys_pending.key_down = true;
3063                                         break;
3064                                 break;
3065                                 default:
3066                                         //can't happen at all!
3067                                         assert("reached a source line that can't ever been reached" == 0);
3068                                         break;
3069                         }
3070                         if (current_keys_pending.key_enter && m_allowclose) {
3071                                 acceptInput(quit_mode_accept);
3072                                 quitMenu();
3073                         } else {
3074                                 acceptInput();
3075                         }
3076                         return true;
3077                 }
3078
3079         }
3080
3081         /* Mouse event other than movement, or crossing the border of inventory
3082           field while holding right mouse button
3083          */
3084         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3085                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3086                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3087                           event.MouseInput.isRightPressed() &&
3088                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3089
3090                 // Get selected item and hovered/clicked item (s)
3091
3092                 m_old_tooltip_id = -1;
3093                 updateSelectedItem();
3094                 ItemSpec s = getItemAtPos(m_pointer);
3095
3096                 Inventory *inv_selected = NULL;
3097                 Inventory *inv_s = NULL;
3098
3099                 if(m_selected_item) {
3100                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3101                         assert(inv_selected);
3102                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
3103                 }
3104
3105                 u32 s_count = 0;
3106
3107                 if(s.isValid())
3108                 do { // breakable
3109                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3110
3111                         if(!inv_s) {
3112                                 errorstream<<"InventoryMenu: The selected inventory location "
3113                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
3114                                                 <<std::endl;
3115                                 s.i = -1;  // make it invalid again
3116                                 break;
3117                         }
3118
3119                         InventoryList *list = inv_s->getList(s.listname);
3120                         if(list == NULL) {
3121                                 verbosestream<<"InventoryMenu: The selected inventory list \""
3122                                                 <<s.listname<<"\" does not exist"<<std::endl;
3123                                 s.i = -1;  // make it invalid again
3124                                 break;
3125                         }
3126
3127                         if((u32)s.i >= list->getSize()) {
3128                                 infostream<<"InventoryMenu: The selected inventory list \""
3129                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
3130                                                 <<list->getSize()<<")"<<std::endl;
3131                                 s.i = -1;  // make it invalid again
3132                                 break;
3133                         }
3134
3135                         s_count = list->getItem(s.i).count;
3136                 } while(0);
3137
3138                 bool identical = (m_selected_item != NULL) && s.isValid() &&
3139                         (inv_selected == inv_s) &&
3140                         (m_selected_item->listname == s.listname) &&
3141                         (m_selected_item->i == s.i);
3142
3143                 // buttons: 0 = left, 1 = right, 2 = middle
3144                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event, -1 movement
3145                 int button = 0;
3146                 int updown = 2;
3147                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
3148                         { button = 0; updown = 0; }
3149                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
3150                         { button = 1; updown = 0; }
3151                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
3152                         { button = 2; updown = 0; }
3153                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
3154                         { button = 0; updown = 1; }
3155                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
3156                         { button = 1; updown = 1; }
3157                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
3158                         { button = 2; updown = 1; }
3159                 else if(event.MouseInput.Event == EMIE_MOUSE_MOVED)
3160                         { updown = -1;}
3161
3162                 // Set this number to a positive value to generate a move action
3163                 // from m_selected_item to s.
3164                 u32 move_amount = 0;
3165
3166                 // Set this number to a positive value to generate a drop action
3167                 // from m_selected_item.
3168                 u32 drop_amount = 0;
3169
3170                 // Set this number to a positive value to generate a craft action at s.
3171                 u32 craft_amount = 0;
3172
3173                 if(updown == 0) {
3174                         // Some mouse button has been pressed
3175
3176                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3177                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3178
3179                         m_selected_dragging = false;
3180
3181                         if(s.isValid() && s.listname == "craftpreview") {
3182                                 // Craft preview has been clicked: craft
3183                                 craft_amount = (button == 2 ? 10 : 1);
3184                         }
3185                         else if(m_selected_item == NULL) {
3186                                 if(s_count != 0) {
3187                                         // Non-empty stack has been clicked: select it
3188                                         m_selected_item = new ItemSpec(s);
3189
3190                                         if(button == 1)  // right
3191                                                 m_selected_amount = (s_count + 1) / 2;
3192                                         else if(button == 2)  // middle
3193                                                 m_selected_amount = MYMIN(s_count, 10);
3194                                         else  // left
3195                                                 m_selected_amount = s_count;
3196
3197                                         m_selected_dragging = true;
3198                                         m_rmouse_auto_place = false;
3199                                 }
3200                         }
3201                         else { // m_selected_item != NULL
3202                                 assert(m_selected_amount >= 1);
3203
3204                                 if(s.isValid()) {
3205                                         // Clicked a slot: move
3206                                         if(button == 1)  // right
3207                                                 move_amount = 1;
3208                                         else if(button == 2)  // middle
3209                                                 move_amount = MYMIN(m_selected_amount, 10);
3210                                         else  // left
3211                                                 move_amount = m_selected_amount;
3212
3213                                         if(identical) {
3214                                                 if(move_amount >= m_selected_amount)
3215                                                         m_selected_amount = 0;
3216                                                 else
3217                                                         m_selected_amount -= move_amount;
3218                                                 move_amount = 0;
3219                                         }
3220                                 }
3221                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3222                                         // Clicked outside of the window: drop
3223                                         if(button == 1)  // right
3224                                                 drop_amount = 1;
3225                                         else if(button == 2)  // middle
3226                                                 drop_amount = MYMIN(m_selected_amount, 10);
3227                                         else  // left
3228                                                 drop_amount = m_selected_amount;
3229                                 }
3230                         }
3231                 }
3232                 else if(updown == 1) {
3233                         // Some mouse button has been released
3234
3235                         //infostream<<"Mouse button "<<button<<" released at p=("
3236                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3237
3238                         if(m_selected_item != NULL && m_selected_dragging && s.isValid()) {
3239                                 if(!identical) {
3240                                         // Dragged to different slot: move all selected
3241                                         move_amount = m_selected_amount;
3242                                 }
3243                         }
3244                         else if(m_selected_item != NULL && m_selected_dragging &&
3245                                 !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
3246                                 // Dragged outside of window: drop all selected
3247                                 drop_amount = m_selected_amount;
3248                         }
3249
3250                         m_selected_dragging = false;
3251                         // Keep count of how many times right mouse button has been
3252                         // clicked. One click is drag without dropping. Click + release
3253                         // + click changes to drop one item when moved mode
3254                         if(button == 1 && m_selected_item != NULL)
3255                                 m_rmouse_auto_place = !m_rmouse_auto_place;
3256                 }
3257                 else if(updown == -1) {
3258                         // Mouse has been moved and rmb is down and mouse pointer just
3259                         // entered a new inventory field (checked in the entry-if, this
3260                         // is the only action here that is generated by mouse movement)
3261                         if(m_selected_item != NULL && s.isValid()){
3262                                 // Move 1 item
3263                                 // TODO: middle mouse to move 10 items might be handy
3264                                 if (m_rmouse_auto_place) {
3265                                         // Only move an item if the destination slot is empty
3266                                         // or contains the same item type as what is going to be
3267                                         // moved
3268                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3269                                         InventoryList *list_to = inv_s->getList(s.listname);
3270                                         assert(list_from && list_to);
3271                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3272                                         ItemStack stack_to = list_to->getItem(s.i);
3273                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3274                                                 move_amount = 1;
3275                                 }
3276                         }
3277                 }
3278
3279                 // Possibly send inventory action to server
3280                 if(move_amount > 0)
3281                 {
3282                         // Send IACTION_MOVE
3283
3284                         assert(m_selected_item && m_selected_item->isValid());
3285                         assert(s.isValid());
3286
3287                         assert(inv_selected && inv_s);
3288                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3289                         InventoryList *list_to = inv_s->getList(s.listname);
3290                         assert(list_from && list_to);
3291                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3292                         ItemStack stack_to = list_to->getItem(s.i);
3293
3294                         // Check how many items can be moved
3295                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3296                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
3297                         // If source stack cannot be added to destination stack at all,
3298                         // they are swapped
3299                         if ((leftover.count == stack_from.count) &&
3300                                         (leftover.name == stack_from.name)) {
3301                                 m_selected_amount = stack_to.count;
3302                                 // In case the server doesn't directly swap them but instead
3303                                 // moves stack_to somewhere else, set this
3304                                 m_selected_content_guess = stack_to;
3305                                 m_selected_content_guess_inventory = s.inventoryloc;
3306                         }
3307                         // Source stack goes fully into destination stack
3308                         else if(leftover.empty()) {
3309                                 m_selected_amount -= move_amount;
3310                                 m_selected_content_guess = ItemStack(); // Clear
3311                         }
3312                         // Source stack goes partly into destination stack
3313                         else {
3314                                 move_amount -= leftover.count;
3315                                 m_selected_amount -= move_amount;
3316                                 m_selected_content_guess = ItemStack(); // Clear
3317                         }
3318
3319                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
3320                         IMoveAction *a = new IMoveAction();
3321                         a->count = move_amount;
3322                         a->from_inv = m_selected_item->inventoryloc;
3323                         a->from_list = m_selected_item->listname;
3324                         a->from_i = m_selected_item->i;
3325                         a->to_inv = s.inventoryloc;
3326                         a->to_list = s.listname;
3327                         a->to_i = s.i;
3328                         m_invmgr->inventoryAction(a);
3329                 }
3330                 else if(drop_amount > 0) {
3331                         m_selected_content_guess = ItemStack(); // Clear
3332
3333                         // Send IACTION_DROP
3334
3335                         assert(m_selected_item && m_selected_item->isValid());
3336                         assert(inv_selected);
3337                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3338                         assert(list_from);
3339                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3340
3341                         // Check how many items can be dropped
3342                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3343                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3344                         m_selected_amount -= drop_amount;
3345
3346                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
3347                         IDropAction *a = new IDropAction();
3348                         a->count = drop_amount;
3349                         a->from_inv = m_selected_item->inventoryloc;
3350                         a->from_list = m_selected_item->listname;
3351                         a->from_i = m_selected_item->i;
3352                         m_invmgr->inventoryAction(a);
3353                 }
3354                 else if(craft_amount > 0) {
3355                         m_selected_content_guess = ItemStack(); // Clear
3356
3357                         // Send IACTION_CRAFT
3358
3359                         assert(s.isValid());
3360                         assert(inv_s);
3361
3362                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
3363                         ICraftAction *a = new ICraftAction();
3364                         a->count = craft_amount;
3365                         a->craft_inv = s.inventoryloc;
3366                         m_invmgr->inventoryAction(a);
3367                 }
3368
3369                 // If m_selected_amount has been decreased to zero, deselect
3370                 if(m_selected_amount == 0) {
3371                         delete m_selected_item;
3372                         m_selected_item = NULL;
3373                         m_selected_amount = 0;
3374                         m_selected_dragging = false;
3375                         m_selected_content_guess = ItemStack();
3376                 }
3377                 m_old_pointer = m_pointer;
3378         }
3379         if(event.EventType==EET_GUI_EVENT) {
3380
3381                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
3382                                 && isVisible()) {
3383                         // find the element that was clicked
3384                         for(unsigned int i=0; i<m_fields.size(); i++) {
3385                                 FieldSpec &s = m_fields[i];
3386                                 if ((s.ftype == f_TabHeader) &&
3387                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3388                                         s.send = true;
3389                                         acceptInput();
3390                                         s.send = false;
3391                                         return true;
3392                                 }
3393                         }
3394                 }
3395                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
3396                                 && isVisible()) {
3397                         if(!canTakeFocus(event.GUIEvent.Element)) {
3398                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
3399                                                 <<std::endl;
3400                                 // Returning true disables focus change
3401                                 return true;
3402                         }
3403                 }
3404                 if((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
3405                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
3406                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
3407                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
3408                         unsigned int btn_id = event.GUIEvent.Caller->getID();
3409
3410                         if (btn_id == 257) {
3411                                 if (m_allowclose) {
3412                                         acceptInput(quit_mode_accept);
3413                                         quitMenu();
3414                                 } else {
3415                                         acceptInput();
3416                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3417                                 }
3418                                 // quitMenu deallocates menu
3419                                 return true;
3420                         }
3421
3422                         // find the element that was clicked
3423                         for(u32 i=0; i<m_fields.size(); i++) {
3424                                 FieldSpec &s = m_fields[i];
3425                                 // if its a button, set the send field so
3426                                 // lua knows which button was pressed
3427                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
3428                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3429                                         s.send = true;
3430                                         if(s.is_exit) {
3431                                                 if (m_allowclose) {
3432                                                         acceptInput(quit_mode_accept);
3433                                                         quitMenu();
3434                                                 } else {
3435                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3436                                                 }
3437                                                 return true;
3438                                         } else {
3439                                                 acceptInput(quit_mode_no);
3440                                                 s.send = false;
3441                                                 return true;
3442                                         }
3443                                 }
3444                                 else if ((s.ftype == f_DropDown) &&
3445                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3446                                         // only send the changed dropdown
3447                                         for(u32 i=0; i<m_fields.size(); i++) {
3448                                                 FieldSpec &s2 = m_fields[i];
3449                                                 if (s2.ftype == f_DropDown) {
3450                                                         s2.send = false;
3451                                                 }
3452                                         }
3453                                         s.send = true;
3454                                         acceptInput(quit_mode_no);
3455
3456                                         // revert configuration to make sure dropdowns are sent on
3457                                         // regular button click
3458                                         for(u32 i=0; i<m_fields.size(); i++) {
3459                                                 FieldSpec &s2 = m_fields[i];
3460                                                 if (s2.ftype == f_DropDown) {
3461                                                         s2.send = true;
3462                                                 }
3463                                         }
3464                                         return true;
3465                                 }
3466                                 else if ((s.ftype == f_ScrollBar) &&
3467                                         (s.fid == event.GUIEvent.Caller->getID()))
3468                                 {
3469                                         s.fdefault = L"Changed";
3470                                         acceptInput(quit_mode_no);
3471                                         s.fdefault = L"";
3472                                 }
3473                         }
3474                 }
3475
3476                 if(event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
3477                         if(event.GUIEvent.Caller->getID() > 257) {
3478
3479                                 if (m_allowclose) {
3480                                         acceptInput(quit_mode_accept);
3481                                         quitMenu();
3482                                 } else {
3483                                         current_keys_pending.key_enter = true;
3484                                         acceptInput();
3485                                 }
3486                                 // quitMenu deallocates menu
3487                                 return true;
3488                         }
3489                 }
3490
3491                 if(event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
3492                         int current_id = event.GUIEvent.Caller->getID();
3493                         if(current_id > 257) {
3494                                 // find the element that was clicked
3495                                 for(u32 i=0; i<m_fields.size(); i++) {
3496                                         FieldSpec &s = m_fields[i];
3497                                         // if it's a table, set the send field
3498                                         // so lua knows which table was changed
3499                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
3500                                                 s.send = true;
3501                                                 acceptInput();
3502                                                 s.send=false;
3503                                         }
3504                                 }
3505                                 return true;
3506                         }
3507                 }
3508         }
3509
3510         return Parent ? Parent->OnEvent(event) : false;
3511 }
3512
3513 /**
3514  * get name of element by element id
3515  * @param id of element
3516  * @return name string or empty string
3517  */
3518 std::wstring GUIFormSpecMenu::getNameByID(s32 id)
3519 {
3520         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3521                                 iter != m_fields.end(); iter++) {
3522                 if (iter->fid == id) {
3523                         return iter->fname;
3524                 }
3525         }
3526         return L"";
3527 }
3528
3529 /**
3530  * get label of element by id
3531  * @param id of element
3532  * @return label string or empty string
3533  */
3534 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
3535 {
3536         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3537                                 iter != m_fields.end(); iter++) {
3538                 if (iter->fid == id) {
3539                         return iter->flabel;
3540                 }
3541         }
3542         return L"";
3543 }