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