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