]> git.lizzy.rs Git - minetest.git/blob - src/guiFormSpecMenu.cpp
Fix uninitialized variable Player::local_animation_speed
[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 "client/tile.h" // ITextureSource
41 #include "hud.h" // drawItemStack
42 #include "filesys.h"
43 #include "gettime.h"
44 #include "gettext.h"
45 #include "scripting_game.h"
46 #include "porting.h"
47 #include "main.h"
48 #include "settings.h"
49 #include "client.h"
50 #include "fontengine.h"
51 #include "util/hex.h"
52 #include "util/numeric.h"
53 #include "util/string.h" // for parseColorString()
54
55 #define MY_CHECKPOS(a,b)                                                                                                        \
56         if (v_pos.size() != 2) {                                                                                                \
57                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
58                         << parts[b] << "\"" << std::endl;                                                               \
59                         return;                                                                                                                 \
60         }
61
62 #define MY_CHECKGEOM(a,b)                                                                                                       \
63         if (v_geom.size() != 2) {                                                                                               \
64                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
65                         << parts[b] << "\"" << std::endl;                                                               \
66                         return;                                                                                                                 \
67         }
68 /*
69         GUIFormSpecMenu
70 */
71 static unsigned int font_line_height(gui::IGUIFont *font)
72 {
73         return font->getDimension(L"Ay").Height + font->getKerningHeight();
74 }
75
76 GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev,
77                 gui::IGUIElement* parent, s32 id, IMenuManager *menumgr,
78                 InventoryManager *invmgr, IGameDef *gamedef,
79                 ISimpleTextureSource *tsrc, IFormSource* fsrc, TextDest* tdst,
80                 Client* client, bool remap_dbl_click) :
81         GUIModalMenu(dev->getGUIEnvironment(), parent, id, menumgr),
82         m_device(dev),
83         m_invmgr(invmgr),
84         m_gamedef(gamedef),
85         m_tsrc(tsrc),
86         m_client(client),
87         m_selected_item(NULL),
88         m_selected_amount(0),
89         m_selected_dragging(false),
90         m_tooltip_element(NULL),
91         m_hovered_time(0),
92         m_old_tooltip_id(-1),
93         m_rmouse_auto_place(false),
94         m_allowclose(true),
95         m_lock(false),
96         m_form_src(fsrc),
97         m_text_dst(tdst),
98         m_formspec_version(0),
99         m_focused_element(L""),
100         m_font(NULL),
101         m_remap_dbl_click(remap_dbl_click)
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(unescape_string(parts[1]),
1555                         m_default_tooltip_bgcolor, m_default_tooltip_color);
1556                 return;
1557         } else if (parts.size() == 4) {
1558                 std::string name = parts[0];
1559                 video::SColor tmp_color1, tmp_color2;
1560                 if ( parseColorString(parts[2], tmp_color1, false) && parseColorString(parts[3], tmp_color2, false) ) {
1561                         m_tooltips[narrow_to_wide(name)] = TooltipSpec(unescape_string(parts[1]),
1562                                 tmp_color1, tmp_color2);
1563                         return;
1564                 }
1565         }
1566         errorstream<< "Invalid tooltip element(" << parts.size() << "): '" << element << "'"  << std::endl;
1567 }
1568
1569 bool GUIFormSpecMenu::parseVersionDirect(std::string data)
1570 {
1571         //some prechecks
1572         if (data == "")
1573                 return false;
1574
1575         std::vector<std::string> parts = split(data,'[');
1576
1577         if (parts.size() < 2) {
1578                 return false;
1579         }
1580
1581         if (parts[0] != "formspec_version") {
1582                 return false;
1583         }
1584
1585         if (is_number(parts[1])) {
1586                 m_formspec_version = mystoi(parts[1]);
1587                 return true;
1588         }
1589
1590         return false;
1591 }
1592
1593 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, std::string element)
1594 {
1595         if (element == "")
1596                 return false;
1597
1598         std::vector<std::string> parts = split(element,'[');
1599
1600         if (parts.size() < 2)
1601                 return false;
1602
1603         std::string type = trim(parts[0]);
1604         std::string description = trim(parts[1]);
1605
1606         if (type != "size" && type != "invsize")
1607                 return false;
1608
1609         if (type == "invsize")
1610                 log_deprecated("Deprecated formspec element \"invsize\" is used");
1611
1612         parseSize(data, description);
1613
1614         return true;
1615 }
1616
1617 void GUIFormSpecMenu::parseElement(parserData* data, std::string element)
1618 {
1619         //some prechecks
1620         if (element == "")
1621                 return;
1622
1623         std::vector<std::string> parts = split(element,'[');
1624
1625         // ugly workaround to keep compatibility
1626         if (parts.size() > 2) {
1627                 if (trim(parts[0]) == "image") {
1628                         for (unsigned int i=2;i< parts.size(); i++) {
1629                                 parts[1] += "[" + parts[i];
1630                         }
1631                 }
1632                 else { return; }
1633         }
1634
1635         if (parts.size() < 2) {
1636                 return;
1637         }
1638
1639         std::string type = trim(parts[0]);
1640         std::string description = trim(parts[1]);
1641
1642         if (type == "list") {
1643                 parseList(data,description);
1644                 return;
1645         }
1646
1647         if (type == "checkbox") {
1648                 parseCheckbox(data,description);
1649                 return;
1650         }
1651
1652         if (type == "image") {
1653                 parseImage(data,description);
1654                 return;
1655         }
1656
1657         if (type == "item_image") {
1658                 parseItemImage(data,description);
1659                 return;
1660         }
1661
1662         if ((type == "button") || (type == "button_exit")) {
1663                 parseButton(data,description,type);
1664                 return;
1665         }
1666
1667         if (type == "background") {
1668                 parseBackground(data,description);
1669                 return;
1670         }
1671
1672         if (type == "tableoptions"){
1673                 parseTableOptions(data,description);
1674                 return;
1675         }
1676
1677         if (type == "tablecolumns"){
1678                 parseTableColumns(data,description);
1679                 return;
1680         }
1681
1682         if (type == "table"){
1683                 parseTable(data,description);
1684                 return;
1685         }
1686
1687         if (type == "textlist"){
1688                 parseTextList(data,description);
1689                 return;
1690         }
1691
1692         if (type == "dropdown"){
1693                 parseDropDown(data,description);
1694                 return;
1695         }
1696
1697         if (type == "pwdfield") {
1698                 parsePwdField(data,description);
1699                 return;
1700         }
1701
1702         if ((type == "field") || (type == "textarea")){
1703                 parseField(data,description,type);
1704                 return;
1705         }
1706
1707         if (type == "label") {
1708                 parseLabel(data,description);
1709                 return;
1710         }
1711
1712         if (type == "vertlabel") {
1713                 parseVertLabel(data,description);
1714                 return;
1715         }
1716
1717         if (type == "item_image_button") {
1718                 parseItemImageButton(data,description);
1719                 return;
1720         }
1721
1722         if ((type == "image_button") || (type == "image_button_exit")) {
1723                 parseImageButton(data,description,type);
1724                 return;
1725         }
1726
1727         if (type == "tabheader") {
1728                 parseTabHeader(data,description);
1729                 return;
1730         }
1731
1732         if (type == "box") {
1733                 parseBox(data,description);
1734                 return;
1735         }
1736
1737         if (type == "bgcolor") {
1738                 parseBackgroundColor(data,description);
1739                 return;
1740         }
1741
1742         if (type == "listcolors") {
1743                 parseListColors(data,description);
1744                 return;
1745         }
1746
1747         if (type == "tooltip") {
1748                 parseTooltip(data,description);
1749                 return;
1750         }
1751
1752         if (type == "scrollbar") {
1753                 parseScrollBar(data, description);
1754                 return;
1755         }
1756
1757         // Ignore others
1758         infostream
1759                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1760                 <<std::endl;
1761 }
1762
1763 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1764 {
1765         /* useless to regenerate without a screensize */
1766         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
1767                 return;
1768         }
1769
1770         parserData mydata;
1771
1772         //preserve tables
1773         for (u32 i = 0; i < m_tables.size(); ++i) {
1774                 std::wstring tablename = m_tables[i].first.fname;
1775                 GUITable *table = m_tables[i].second;
1776                 mydata.table_dyndata[tablename] = table->getDynamicData();
1777         }
1778
1779         //set focus
1780         if (!m_focused_element.empty())
1781                 mydata.focused_fieldname = m_focused_element;
1782
1783         //preserve focus
1784         gui::IGUIElement *focused_element = Environment->getFocus();
1785         if (focused_element && focused_element->getParent() == this) {
1786                 s32 focused_id = focused_element->getID();
1787                 if (focused_id > 257) {
1788                         for (u32 i=0; i<m_fields.size(); i++) {
1789                                 if (m_fields[i].fid == focused_id) {
1790                                         mydata.focused_fieldname =
1791                                                 m_fields[i].fname;
1792                                         break;
1793                                 }
1794                         }
1795                 }
1796         }
1797
1798         // Remove children
1799         removeChildren();
1800
1801         for (u32 i = 0; i < m_tables.size(); ++i) {
1802                 GUITable *table = m_tables[i].second;
1803                 table->drop();
1804         }
1805
1806         mydata.size= v2s32(100,100);
1807         mydata.screensize = screensize;
1808
1809         // Base position of contents of form
1810         mydata.basepos = getBasePos();
1811
1812         /* Convert m_init_draw_spec to m_inventorylists */
1813
1814         m_inventorylists.clear();
1815         m_images.clear();
1816         m_backgrounds.clear();
1817         m_itemimages.clear();
1818         m_tables.clear();
1819         m_checkboxes.clear();
1820         m_scrollbars.clear();
1821         m_fields.clear();
1822         m_boxes.clear();
1823         m_tooltips.clear();
1824
1825         // Set default values (fits old formspec values)
1826         m_bgcolor = video::SColor(140,0,0,0);
1827         m_bgfullscreen = false;
1828
1829         m_slotbg_n = video::SColor(255,128,128,128);
1830         m_slotbg_h = video::SColor(255,192,192,192);
1831
1832         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
1833         m_default_tooltip_color = video::SColor(255,255,255,255);
1834
1835         m_slotbordercolor = video::SColor(200,0,0,0);
1836         m_slotborder = false;
1837
1838         m_clipbackground = false;
1839         // Add tooltip
1840         {
1841                 assert(m_tooltip_element == NULL);
1842                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
1843                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
1844                 m_tooltip_element->enableOverrideColor(true);
1845                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
1846                 m_tooltip_element->setDrawBackground(true);
1847                 m_tooltip_element->setDrawBorder(true);
1848                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
1849                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1850                 m_tooltip_element->setWordWrap(false);
1851                 //we're not parent so no autograb for this one!
1852                 m_tooltip_element->grab();
1853         }
1854
1855         std::vector<std::string> elements = split(m_formspec_string,']');
1856         unsigned int i = 0;
1857
1858         /* try to read version from first element only */
1859         if (elements.size() >= 1) {
1860                 if ( parseVersionDirect(elements[0]) ) {
1861                         i++;
1862                 }
1863         }
1864
1865         /* we need size first in order to calculate image scale */
1866         mydata.explicit_size = false;
1867         for (; i< elements.size(); i++) {
1868                 if (!parseSizeDirect(&mydata, elements[i])) {
1869                         break;
1870                 }
1871         }
1872
1873         if (mydata.explicit_size) {
1874                 // compute scaling for specified form size
1875                 if (m_lock) {
1876                         v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize();
1877                         v2u32 delta = current_screensize - m_lockscreensize;
1878
1879                         if (current_screensize.Y > m_lockscreensize.Y)
1880                                 delta.Y /= 2;
1881                         else
1882                                 delta.Y = 0;
1883
1884                         if (current_screensize.X > m_lockscreensize.X)
1885                                 delta.X /= 2;
1886                         else
1887                                 delta.X = 0;
1888
1889                         offset = v2s32(delta.X,delta.Y);
1890
1891                         mydata.screensize = m_lockscreensize;
1892                 } else {
1893                         offset = v2s32(0,0);
1894                 }
1895
1896                 double gui_scaling = g_settings->getFloat("gui_scaling");
1897                 double screen_dpi = porting::getDisplayDensity() * 96;
1898
1899                 double use_imgsize;
1900                 if (m_lock) {
1901                         // In fixed-size mode, inventory image size
1902                         // is 0.53 inch multiplied by the gui_scaling
1903                         // config parameter.  This magic size is chosen
1904                         // to make the main menu (15.5 inventory images
1905                         // wide, including border) just fit into the
1906                         // default window (800 pixels wide) at 96 DPI
1907                         // and default scaling (1.00).
1908                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
1909                 } else {
1910                         // In variable-size mode, we prefer to make the
1911                         // inventory image size 1/15 of screen height,
1912                         // multiplied by the gui_scaling config parameter.
1913                         // If the preferred size won't fit the whole
1914                         // form on the screen, either horizontally or
1915                         // vertically, then we scale it down to fit.
1916                         // (The magic numbers in the computation of what
1917                         // fits arise from the scaling factors in the
1918                         // following stanza, including the form border,
1919                         // help text space, and 0.1 inventory slot spare.)
1920                         // However, a minimum size is also set, that
1921                         // the image size can't be less than 0.3 inch
1922                         // multiplied by gui_scaling, even if this means
1923                         // the form doesn't fit the screen.
1924                         double prefer_imgsize = mydata.screensize.Y / 15 *
1925                                                         gui_scaling;
1926                         double fitx_imgsize = mydata.screensize.X /
1927                                 ((5.0/4.0) * (0.5 + mydata.invsize.X));
1928                         double fity_imgsize = mydata.screensize.Y /
1929                                 ((15.0/13.0) * (0.85 * mydata.invsize.Y));
1930                         double screen_dpi = porting::getDisplayDensity() * 96;
1931                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
1932                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
1933                                 MYMIN(fitx_imgsize, fity_imgsize)));
1934                 }
1935
1936                 // Everything else is scaled in proportion to the
1937                 // inventory image size.  The inventory slot spacing
1938                 // is 5/4 image size horizontally and 15/13 image size
1939                 // vertically.  The padding around the form (incorporating
1940                 // the border of the outer inventory slots) is 3/8
1941                 // image size.  Font height (baseline to baseline)
1942                 // is 2/5 vertical inventory slot spacing, and button
1943                 // half-height is 7/8 of font height.
1944                 imgsize = v2s32(use_imgsize, use_imgsize);
1945                 spacing = v2s32(use_imgsize*5.0/4, use_imgsize*15.0/13);
1946                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
1947                 m_btn_height = use_imgsize*15.0/13 * 0.35;
1948
1949                 m_font = g_fontengine->getFont();
1950
1951                 mydata.size = v2s32(
1952                         padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
1953                         padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
1954                 );
1955                 DesiredRect = mydata.rect = core::rect<s32>(
1956                                 mydata.screensize.X/2 - mydata.size.X/2 + offset.X,
1957                                 mydata.screensize.Y/2 - mydata.size.Y/2 + offset.Y,
1958                                 mydata.screensize.X/2 + mydata.size.X/2 + offset.X,
1959                                 mydata.screensize.Y/2 + mydata.size.Y/2 + offset.Y
1960                 );
1961         } else {
1962                 // Non-size[] form must consist only of text fields and
1963                 // implicit "Proceed" button.  Use default font, and
1964                 // temporary form size which will be recalculated below.
1965                 m_font = g_fontengine->getFont();
1966                 m_btn_height = font_line_height(m_font) * 0.875;
1967                 DesiredRect = core::rect<s32>(
1968                         mydata.screensize.X/2 - 580/2,
1969                         mydata.screensize.Y/2 - 300/2,
1970                         mydata.screensize.X/2 + 580/2,
1971                         mydata.screensize.Y/2 + 300/2
1972                 );
1973         }
1974         recalculateAbsolutePosition(false);
1975         mydata.basepos = getBasePos();
1976         m_tooltip_element->setOverrideFont(m_font);
1977
1978         gui::IGUISkin* skin = Environment->getSkin();
1979         sanity_check(skin != NULL);
1980         gui::IGUIFont *old_font = skin->getFont();
1981         skin->setFont(m_font);
1982
1983         for (; i< elements.size(); i++) {
1984                 parseElement(&mydata, elements[i]);
1985         }
1986
1987         // If there are fields without explicit size[], add a "Proceed"
1988         // button and adjust size to fit all the fields.
1989         if (m_fields.size() && !mydata.explicit_size) {
1990                 mydata.rect = core::rect<s32>(
1991                                 mydata.screensize.X/2 - 580/2,
1992                                 mydata.screensize.Y/2 - 300/2,
1993                                 mydata.screensize.X/2 + 580/2,
1994                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
1995                 );
1996                 DesiredRect = mydata.rect;
1997                 recalculateAbsolutePosition(false);
1998                 mydata.basepos = getBasePos();
1999
2000                 {
2001                         v2s32 pos = mydata.basepos;
2002                         pos.Y = ((m_fields.size()+2)*60);
2003
2004                         v2s32 size = DesiredRect.getSize();
2005                         mydata.rect =
2006                                         core::rect<s32>(size.X/2-70, pos.Y,
2007                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2008                         const wchar_t *text = wgettext("Proceed");
2009                         Environment->addButton(mydata.rect, this, 257, text);
2010                         delete[] text;
2011                 }
2012
2013         }
2014
2015         //set initial focus if parser didn't set it
2016         focused_element = Environment->getFocus();
2017         if (!focused_element
2018                         || !isMyChild(focused_element)
2019                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2020                 setInitialFocus();
2021
2022         skin->setFont(old_font);
2023 }
2024
2025 #ifdef __ANDROID__
2026 bool GUIFormSpecMenu::getAndroidUIInput()
2027 {
2028         /* no dialog shown */
2029         if (m_JavaDialogFieldName == L"") {
2030                 return false;
2031         }
2032
2033         /* still waiting */
2034         if (porting::getInputDialogState() == -1) {
2035                 return true;
2036         }
2037
2038         std::wstring fieldname = m_JavaDialogFieldName;
2039         m_JavaDialogFieldName = L"";
2040
2041         /* no value abort dialog processing */
2042         if (porting::getInputDialogState() != 0) {
2043                 return false;
2044         }
2045
2046         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2047                         iter != m_fields.end(); iter++) {
2048
2049                 if (iter->fname != fieldname) {
2050                         continue;
2051                 }
2052                 IGUIElement* tochange = getElementFromId(iter->fid);
2053
2054                 if (tochange == 0) {
2055                         return false;
2056                 }
2057
2058                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2059                         return false;
2060                 }
2061
2062                 std::string text = porting::getInputDialogValue();
2063
2064                 ((gui::IGUIEditBox*) tochange)->
2065                         setText(narrow_to_wide(text).c_str());
2066         }
2067         return false;
2068 }
2069 #endif
2070
2071 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2072 {
2073         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2074
2075         for(u32 i=0; i<m_inventorylists.size(); i++)
2076         {
2077                 const ListDrawSpec &s = m_inventorylists[i];
2078
2079                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2080                         s32 item_i = i + s.start_item_i;
2081                         s32 x = (i%s.geom.X) * spacing.X;
2082                         s32 y = (i/s.geom.X) * spacing.Y;
2083                         v2s32 p0(x,y);
2084                         core::rect<s32> rect = imgrect + s.pos + p0;
2085                         if(rect.isPointInside(p))
2086                         {
2087                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2088                         }
2089                 }
2090         }
2091
2092         return ItemSpec(InventoryLocation(), "", -1);
2093 }
2094
2095 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
2096 {
2097         video::IVideoDriver* driver = Environment->getVideoDriver();
2098
2099         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2100         if(!inv){
2101                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2102                                 <<"The inventory location "
2103                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2104                                 <<std::endl;
2105                 return;
2106         }
2107         InventoryList *ilist = inv->getList(s.listname);
2108         if(!ilist){
2109                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2110                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2111                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2112                                 <<std::endl;
2113                 return;
2114         }
2115
2116         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2117
2118         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
2119         {
2120                 s32 item_i = i + s.start_item_i;
2121                 if(item_i >= (s32) ilist->getSize())
2122                         break;
2123                 s32 x = (i%s.geom.X) * spacing.X;
2124                 s32 y = (i/s.geom.X) * spacing.Y;
2125                 v2s32 p(x,y);
2126                 core::rect<s32> rect = imgrect + s.pos + p;
2127                 ItemStack item;
2128                 if(ilist)
2129                         item = ilist->getItem(item_i);
2130
2131                 bool selected = m_selected_item
2132                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2133                         && m_selected_item->listname == s.listname
2134                         && m_selected_item->i == item_i;
2135                 bool hovering = rect.isPointInside(m_pointer);
2136
2137                 if(phase == 0)
2138                 {
2139                         if(hovering)
2140                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2141                         else
2142                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2143                 }
2144
2145                 //Draw inv slot borders
2146                 if (m_slotborder) {
2147                         s32 x1 = rect.UpperLeftCorner.X;
2148                         s32 y1 = rect.UpperLeftCorner.Y;
2149                         s32 x2 = rect.LowerRightCorner.X;
2150                         s32 y2 = rect.LowerRightCorner.Y;
2151                         s32 border = 1;
2152                         driver->draw2DRectangle(m_slotbordercolor,
2153                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2154                                                                 v2s32(x2 + border, y1)), NULL);
2155                         driver->draw2DRectangle(m_slotbordercolor,
2156                                 core::rect<s32>(v2s32(x1 - border, y2),
2157                                                                 v2s32(x2 + border, y2 + border)), NULL);
2158                         driver->draw2DRectangle(m_slotbordercolor,
2159                                 core::rect<s32>(v2s32(x1 - border, y1),
2160                                                                 v2s32(x1, y2)), NULL);
2161                         driver->draw2DRectangle(m_slotbordercolor,
2162                                 core::rect<s32>(v2s32(x2, y1),
2163                                                                 v2s32(x2 + border, y2)), NULL);
2164                 }
2165
2166                 if(phase == 1)
2167                 {
2168                         // Draw item stack
2169                         if(selected)
2170                         {
2171                                 item.takeItem(m_selected_amount);
2172                         }
2173                         if(!item.empty())
2174                         {
2175                                 drawItemStack(driver, m_font, item,
2176                                                 rect, &AbsoluteClippingRect, m_gamedef);
2177                         }
2178
2179                         // Draw tooltip
2180                         std::string tooltip_text = "";
2181                         if (hovering && !m_selected_item)
2182                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
2183                         if (tooltip_text != "") {
2184                                 std::vector<std::string> tt_rows = str_split(tooltip_text, '\n');
2185                                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2186                                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2187                                 m_tooltip_element->setVisible(true);
2188                                 this->bringToFront(m_tooltip_element);
2189                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
2190                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2191                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2192                                 v2u32 screenSize = driver->getScreenSize();
2193                                 int tooltip_offset_x = m_btn_height;
2194                                 int tooltip_offset_y = m_btn_height;
2195 #ifdef __ANDROID__
2196                                 tooltip_offset_x *= 3;
2197                                 tooltip_offset_y  = 0;
2198                                 if (m_pointer.X > (s32)screenSize.X / 2)
2199                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2200 #endif
2201                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2202                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2203                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2204                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2205                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2206                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2207                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2208                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2209                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2210                         }
2211                 }
2212         }
2213 }
2214
2215 void GUIFormSpecMenu::drawSelectedItem()
2216 {
2217         if(!m_selected_item)
2218                 return;
2219
2220         video::IVideoDriver* driver = Environment->getVideoDriver();
2221
2222         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2223         sanity_check(inv);
2224         InventoryList *list = inv->getList(m_selected_item->listname);
2225         sanity_check(list);
2226         ItemStack stack = list->getItem(m_selected_item->i);
2227         stack.count = m_selected_amount;
2228
2229         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2230         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2231         drawItemStack(driver, m_font, stack, rect, NULL, m_gamedef);
2232 }
2233
2234 void GUIFormSpecMenu::drawMenu()
2235 {
2236         if(m_form_src){
2237                 std::string newform = m_form_src->getForm();
2238                 if(newform != m_formspec_string){
2239                         m_formspec_string = newform;
2240                         regenerateGui(m_screensize_old);
2241                 }
2242         }
2243
2244         gui::IGUISkin* skin = Environment->getSkin();
2245         sanity_check(skin != NULL);
2246         gui::IGUIFont *old_font = skin->getFont();
2247         skin->setFont(m_font);
2248
2249         updateSelectedItem();
2250
2251         video::IVideoDriver* driver = Environment->getVideoDriver();
2252
2253         v2u32 screenSize = driver->getScreenSize();
2254         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
2255         if (m_bgfullscreen)
2256                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
2257         else
2258                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2259
2260         m_tooltip_element->setVisible(false);
2261
2262         /*
2263                 Draw backgrounds
2264         */
2265         for(u32 i=0; i<m_backgrounds.size(); i++)
2266         {
2267                 const ImageDrawSpec &spec = m_backgrounds[i];
2268                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2269
2270                 if (texture != 0) {
2271                         // Image size on screen
2272                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2273                         // Image rectangle on screen
2274                         core::rect<s32> rect = imgrect + spec.pos;
2275
2276                         if (m_clipbackground) {
2277                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2278                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2279                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2280                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2281                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2282                         }
2283
2284                         const video::SColor color(255,255,255,255);
2285                         const video::SColor colors[] = {color,color,color,color};
2286                         driver->draw2DImage(texture, rect,
2287                                 core::rect<s32>(core::position2d<s32>(0,0),
2288                                                 core::dimension2di(texture->getOriginalSize())),
2289                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2290                 }
2291                 else {
2292                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2293                         errorstream << "\t" << spec.name << std::endl;
2294                 }
2295         }
2296
2297         /*
2298                 Draw Boxes
2299         */
2300         for(u32 i=0; i<m_boxes.size(); i++)
2301         {
2302                 const BoxDrawSpec &spec = m_boxes[i];
2303
2304                 irr::video::SColor todraw = spec.color;
2305
2306                 todraw.setAlpha(140);
2307
2308                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2309                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2310
2311                 driver->draw2DRectangle(todraw, rect, 0);
2312         }
2313         /*
2314                 Draw images
2315         */
2316         for(u32 i=0; i<m_images.size(); i++)
2317         {
2318                 const ImageDrawSpec &spec = m_images[i];
2319                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2320
2321                 if (texture != 0) {
2322                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2323                         // Image size on screen
2324                         core::rect<s32> imgrect;
2325
2326                         if (spec.scale)
2327                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2328                         else {
2329
2330                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2331                         }
2332                         // Image rectangle on screen
2333                         core::rect<s32> rect = imgrect + spec.pos;
2334                         const video::SColor color(255,255,255,255);
2335                         const video::SColor colors[] = {color,color,color,color};
2336                         driver->draw2DImage(texture, rect,
2337                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2338                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2339                 }
2340                 else {
2341                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2342                         errorstream << "\t" << spec.name << std::endl;
2343                 }
2344         }
2345
2346         /*
2347                 Draw item images
2348         */
2349         for(u32 i=0; i<m_itemimages.size(); i++)
2350         {
2351                 if (m_gamedef == 0)
2352                         break;
2353
2354                 const ImageDrawSpec &spec = m_itemimages[i];
2355                 IItemDefManager *idef = m_gamedef->idef();
2356                 ItemStack item;
2357                 item.deSerialize(spec.name, idef);
2358                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
2359                 // Image size on screen
2360                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2361                 // Image rectangle on screen
2362                 core::rect<s32> rect = imgrect + spec.pos;
2363                 const video::SColor color(255,255,255,255);
2364                 const video::SColor colors[] = {color,color,color,color};
2365                 driver->draw2DImage(texture, rect,
2366                         core::rect<s32>(core::position2d<s32>(0,0),
2367                                         core::dimension2di(texture->getOriginalSize())),
2368                         NULL/*&AbsoluteClippingRect*/, colors, true);
2369         }
2370
2371         /*
2372                 Draw items
2373                 Phase 0: Item slot rectangles
2374                 Phase 1: Item images; prepare tooltip
2375         */
2376         int start_phase=0;
2377         for(int phase=start_phase; phase<=1; phase++)
2378         for(u32 i=0; i<m_inventorylists.size(); i++)
2379         {
2380                 drawList(m_inventorylists[i], phase);
2381         }
2382
2383         /*
2384                 Call base class
2385         */
2386         gui::IGUIElement::draw();
2387
2388 /* TODO find way to show tooltips on touchscreen */
2389 #ifndef HAVE_TOUCHSCREENGUI
2390         m_pointer = m_device->getCursorControl()->getPosition();
2391 #endif
2392
2393         /*
2394                 Draw fields/buttons tooltips
2395         */
2396         gui::IGUIElement *hovered =
2397                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2398
2399         if (hovered != NULL) {
2400                 s32 id = hovered->getID();
2401
2402                 u32 delta = 0;
2403                 if (id == -1) {
2404                         m_old_tooltip_id = id;
2405                         m_old_tooltip = "";
2406                 } else {
2407                         if (id == m_old_tooltip_id) {
2408                                 delta = porting::getDeltaMs(m_hovered_time, getTimeMs());
2409                         } else {
2410                                 m_hovered_time = getTimeMs();
2411                                 m_old_tooltip_id = id;
2412                         }
2413                 }
2414
2415                 if (id != -1 && delta >= m_tooltip_show_delay) {
2416                         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2417                                         iter != m_fields.end(); iter++) {
2418                                 if ( (iter->fid == id) && (m_tooltips[iter->fname].tooltip != "") ){
2419                                         if (m_old_tooltip != m_tooltips[iter->fname].tooltip) {
2420                                                 m_old_tooltip = m_tooltips[iter->fname].tooltip;
2421                                                 m_tooltip_element->setText(narrow_to_wide(m_tooltips[iter->fname].tooltip).c_str());
2422                                                 std::vector<std::string> tt_rows = str_split(m_tooltips[iter->fname].tooltip, '\n');
2423                                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2424                                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2425                                                 int tooltip_offset_x = m_btn_height;
2426                                                 int tooltip_offset_y = m_btn_height;
2427 #ifdef __ANDROID__
2428                                                 tooltip_offset_x *= 3;
2429                                                 tooltip_offset_y  = 0;
2430                                                 if (m_pointer.X > (s32)screenSize.X / 2)
2431                                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2432 #endif
2433                                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2434                                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2435                                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2436                                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2437                                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2438                                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2439                                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2440                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2441                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2442                                         }
2443                                         m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor);
2444                                         m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color);
2445                                         m_tooltip_element->setVisible(true);
2446                                         this->bringToFront(m_tooltip_element);
2447                                         break;
2448                                 }
2449                         }
2450                 }
2451         }
2452
2453         /*
2454                 Draw dragged item stack
2455         */
2456         drawSelectedItem();
2457
2458         skin->setFont(old_font);
2459 }
2460
2461 void GUIFormSpecMenu::updateSelectedItem()
2462 {
2463         // If the selected stack has become empty for some reason, deselect it.
2464         // If the selected stack has become inaccessible, deselect it.
2465         // If the selected stack has become smaller, adjust m_selected_amount.
2466         ItemStack selected = verifySelectedItem();
2467
2468         // WARNING: BLACK MAGIC
2469         // See if there is a stack suited for our current guess.
2470         // If such stack does not exist, clear the guess.
2471         if(m_selected_content_guess.name != "" &&
2472                         selected.name == m_selected_content_guess.name &&
2473                         selected.count == m_selected_content_guess.count){
2474                 // Selected item fits the guess. Skip the black magic.
2475         }
2476         else if(m_selected_content_guess.name != ""){
2477                 bool found = false;
2478                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2479                         const ListDrawSpec &s = m_inventorylists[i];
2480                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2481                         if(!inv)
2482                                 continue;
2483                         InventoryList *list = inv->getList(s.listname);
2484                         if(!list)
2485                                 continue;
2486                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2487                                 u32 item_i = i + s.start_item_i;
2488                                 if(item_i >= list->getSize())
2489                                         continue;
2490                                 ItemStack stack = list->getItem(item_i);
2491                                 if(stack.name == m_selected_content_guess.name &&
2492                                                 stack.count == m_selected_content_guess.count){
2493                                         found = true;
2494                                         infostream<<"Client: Changing selected content guess to "
2495                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2496                                                         <<" "<<item_i<<std::endl;
2497                                         delete m_selected_item;
2498                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2499                                         m_selected_amount = stack.count;
2500                                 }
2501                         }
2502                 }
2503                 if(!found){
2504                         infostream<<"Client: Discarding selected content guess: "
2505                                         <<m_selected_content_guess.getItemString()<<std::endl;
2506                         m_selected_content_guess.name = "";
2507                 }
2508         }
2509
2510         // If craftresult is nonempty and nothing else is selected, select it now.
2511         if(!m_selected_item)
2512         {
2513                 for(u32 i=0; i<m_inventorylists.size(); i++)
2514                 {
2515                         const ListDrawSpec &s = m_inventorylists[i];
2516                         if(s.listname == "craftpreview")
2517                         {
2518                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2519                                 InventoryList *list = inv->getList("craftresult");
2520                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2521                                 {
2522                                         m_selected_item = new ItemSpec;
2523                                         m_selected_item->inventoryloc = s.inventoryloc;
2524                                         m_selected_item->listname = "craftresult";
2525                                         m_selected_item->i = 0;
2526                                         m_selected_amount = 0;
2527                                         m_selected_dragging = false;
2528                                         break;
2529                                 }
2530                         }
2531                 }
2532         }
2533
2534         // If craftresult is selected, keep the whole stack selected
2535         if(m_selected_item && m_selected_item->listname == "craftresult")
2536         {
2537                 m_selected_amount = verifySelectedItem().count;
2538         }
2539 }
2540
2541 ItemStack GUIFormSpecMenu::verifySelectedItem()
2542 {
2543         // If the selected stack has become empty for some reason, deselect it.
2544         // If the selected stack has become inaccessible, deselect it.
2545         // If the selected stack has become smaller, adjust m_selected_amount.
2546         // Return the selected stack.
2547
2548         if(m_selected_item)
2549         {
2550                 if(m_selected_item->isValid())
2551                 {
2552                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2553                         if(inv)
2554                         {
2555                                 InventoryList *list = inv->getList(m_selected_item->listname);
2556                                 if(list && (u32) m_selected_item->i < list->getSize())
2557                                 {
2558                                         ItemStack stack = list->getItem(m_selected_item->i);
2559                                         if(m_selected_amount > stack.count)
2560                                                 m_selected_amount = stack.count;
2561                                         if(!stack.empty())
2562                                                 return stack;
2563                                 }
2564                         }
2565                 }
2566
2567                 // selection was not valid
2568                 delete m_selected_item;
2569                 m_selected_item = NULL;
2570                 m_selected_amount = 0;
2571                 m_selected_dragging = false;
2572         }
2573         return ItemStack();
2574 }
2575
2576 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2577 {
2578         if(m_text_dst)
2579         {
2580                 std::map<std::string, std::string> fields;
2581
2582                 if (quitmode == quit_mode_accept) {
2583                         fields["quit"] = "true";
2584                 }
2585
2586                 if (quitmode == quit_mode_cancel) {
2587                         fields["quit"] = "true";
2588                         m_text_dst->gotText(fields);
2589                         return;
2590                 }
2591
2592                 if (current_keys_pending.key_down) {
2593                         fields["key_down"] = "true";
2594                         current_keys_pending.key_down = false;
2595                 }
2596
2597                 if (current_keys_pending.key_up) {
2598                         fields["key_up"] = "true";
2599                         current_keys_pending.key_up = false;
2600                 }
2601
2602                 if (current_keys_pending.key_enter) {
2603                         fields["key_enter"] = "true";
2604                         current_keys_pending.key_enter = false;
2605                 }
2606
2607                 if (current_keys_pending.key_escape) {
2608                         fields["key_escape"] = "true";
2609                         current_keys_pending.key_escape = false;
2610                 }
2611
2612                 for(unsigned int i=0; i<m_fields.size(); i++) {
2613                         const FieldSpec &s = m_fields[i];
2614                         if(s.send) {
2615                                 std::string name  = wide_to_narrow(s.fname);
2616                                 if(s.ftype == f_Button) {
2617                                         fields[name] = wide_to_narrow(s.flabel);
2618                                 }
2619                                 else if(s.ftype == f_Table) {
2620                                         GUITable *table = getTable(s.fname);
2621                                         if (table) {
2622                                                 fields[name] = table->checkEvent();
2623                                         }
2624                                 }
2625                                 else if(s.ftype == f_DropDown) {
2626                                         // no dynamic cast possible due to some distributions shipped
2627                                         // without rtti support in irrlicht
2628                                         IGUIElement * element = getElementFromId(s.fid);
2629                                         gui::IGUIComboBox *e = NULL;
2630                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2631                                                 e = static_cast<gui::IGUIComboBox*>(element);
2632                                         }
2633                                         s32 selected = e->getSelected();
2634                                         if (selected >= 0) {
2635                                                 fields[name] =
2636                                                         wide_to_narrow(e->getItem(selected));
2637                                         }
2638                                 }
2639                                 else if (s.ftype == f_TabHeader) {
2640                                         // no dynamic cast possible due to some distributions shipped
2641                                         // without rtti support in irrlicht
2642                                         IGUIElement * element = getElementFromId(s.fid);
2643                                         gui::IGUITabControl *e = NULL;
2644                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2645                                                 e = static_cast<gui::IGUITabControl*>(element);
2646                                         }
2647
2648                                         if (e != 0) {
2649                                                 std::stringstream ss;
2650                                                 ss << (e->getActiveTab() +1);
2651                                                 fields[name] = ss.str();
2652                                         }
2653                                 }
2654                                 else if (s.ftype == f_CheckBox) {
2655                                         // no dynamic cast possible due to some distributions shipped
2656                                         // without rtti support in irrlicht
2657                                         IGUIElement * element = getElementFromId(s.fid);
2658                                         gui::IGUICheckBox *e = NULL;
2659                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2660                                                 e = static_cast<gui::IGUICheckBox*>(element);
2661                                         }
2662
2663                                         if (e != 0) {
2664                                                 if (e->isChecked())
2665                                                         fields[name] = "true";
2666                                                 else
2667                                                         fields[name] = "false";
2668                                         }
2669                                 }
2670                                 else if (s.ftype == f_ScrollBar) {
2671                                         // no dynamic cast possible due to some distributions shipped
2672                                         // without rtti support in irrlicht
2673                                         IGUIElement * element = getElementFromId(s.fid);
2674                                         gui::IGUIScrollBar *e = NULL;
2675                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
2676                                                 e = static_cast<gui::IGUIScrollBar*>(element);
2677                                         }
2678
2679                                         if (e != 0) {
2680                                                 std::stringstream os;
2681                                                 os << e->getPos();
2682                                                 if (s.fdefault == L"Changed")
2683                                                         fields[name] = "CHG:" + os.str();
2684                                                 else
2685                                                         fields[name] = "VAL:" + os.str();
2686                                         }
2687                                 }
2688                                 else
2689                                 {
2690                                         IGUIElement* e = getElementFromId(s.fid);
2691                                         if(e != NULL) {
2692                                                 fields[name] = wide_to_narrow(e->getText());
2693                                         }
2694                                 }
2695                         }
2696                 }
2697
2698                 m_text_dst->gotText(fields);
2699         }
2700 }
2701
2702 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2703 {
2704         while(tocheck != NULL) {
2705                 if (tocheck == parent) {
2706                         return true;
2707                 }
2708                 tocheck = tocheck->getParent();
2709         }
2710         return false;
2711 }
2712
2713 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2714 {
2715         // The IGUITabControl renders visually using the skin's selected
2716         // font, which we override for the duration of form drawing,
2717         // but computes tab hotspots based on how it would have rendered
2718         // using the font that is selected at the time of button release.
2719         // To make these two consistent, temporarily override the skin's
2720         // font while the IGUITabControl is processing the event.
2721         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
2722                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2723                 s32 x = event.MouseInput.X;
2724                 s32 y = event.MouseInput.Y;
2725                 gui::IGUIElement *hovered =
2726                         Environment->getRootGUIElement()->getElementFromPoint(
2727                                 core::position2d<s32>(x, y));
2728                 if (hovered && isMyChild(hovered) &&
2729                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
2730                         gui::IGUISkin* skin = Environment->getSkin();
2731                         sanity_check(skin != NULL);
2732                         gui::IGUIFont *old_font = skin->getFont();
2733                         skin->setFont(m_font);
2734                         bool retval = hovered->OnEvent(event);
2735                         skin->setFont(old_font);
2736                         return retval;
2737                 }
2738         }
2739
2740         // Fix Esc/Return key being eaten by checkboxen and tables
2741         if(event.EventType==EET_KEY_INPUT_EVENT) {
2742                 KeyPress kp(event.KeyInput);
2743                 if (kp == EscapeKey || kp == CancelKey
2744                                 || kp == getKeySetting("keymap_inventory")
2745                                 || event.KeyInput.Key==KEY_RETURN) {
2746                         gui::IGUIElement *focused = Environment->getFocus();
2747                         if (focused && isMyChild(focused) &&
2748                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2749                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2750                                 OnEvent(event);
2751                                 return true;
2752                         }
2753                 }
2754         }
2755         // Mouse wheel events: send to hovered element instead of focused
2756         if(event.EventType==EET_MOUSE_INPUT_EVENT
2757                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
2758                 s32 x = event.MouseInput.X;
2759                 s32 y = event.MouseInput.Y;
2760                 gui::IGUIElement *hovered =
2761                         Environment->getRootGUIElement()->getElementFromPoint(
2762                                 core::position2d<s32>(x, y));
2763                 if (hovered && isMyChild(hovered)) {
2764                         hovered->OnEvent(event);
2765                         return true;
2766                 }
2767         }
2768
2769         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
2770                 s32 x = event.MouseInput.X;
2771                 s32 y = event.MouseInput.Y;
2772                 gui::IGUIElement *hovered =
2773                         Environment->getRootGUIElement()->getElementFromPoint(
2774                                 core::position2d<s32>(x, y));
2775                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2776                         m_old_tooltip_id = -1;
2777                         m_old_tooltip = "";
2778                 }
2779                 if (!isChild(hovered,this)) {
2780                         if (DoubleClickDetection(event)) {
2781                                 return true;
2782                         }
2783                 }
2784         }
2785
2786         #ifdef __ANDROID__
2787         // display software keyboard when clicking edit boxes
2788         if (event.EventType == EET_MOUSE_INPUT_EVENT
2789                         && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2790                 gui::IGUIElement *hovered =
2791                         Environment->getRootGUIElement()->getElementFromPoint(
2792                                 core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
2793                 if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) {
2794                         bool retval = hovered->OnEvent(event);
2795                         if (retval) {
2796                                 Environment->setFocus(hovered);
2797                         }
2798                         m_JavaDialogFieldName = getNameByID(hovered->getID());
2799                         std::string message   = gettext("Enter ");
2800                         std::string label     = wide_to_narrow(getLabelByID(hovered->getID()));
2801                         if (label == "") {
2802                                 label = "text";
2803                         }
2804                         message += gettext(label) + ":";
2805
2806                         /* single line text input */
2807                         int type = 2;
2808
2809                         /* multi line text input */
2810                         if (((gui::IGUIEditBox*) hovered)->isMultiLineEnabled()) {
2811                                 type = 1;
2812                         }
2813
2814                         /* passwords are always single line */
2815                         if (((gui::IGUIEditBox*) hovered)->isPasswordBox()) {
2816                                 type = 3;
2817                         }
2818
2819                         porting::showInputDialog(gettext("ok"), "",
2820                                         wide_to_narrow(((gui::IGUIEditBox*) hovered)->getText()),
2821                                         type);
2822                         return retval;
2823                 }
2824         }
2825
2826         if (event.EventType == EET_TOUCH_INPUT_EVENT)
2827         {
2828                 SEvent translated;
2829                 memset(&translated, 0, sizeof(SEvent));
2830                 translated.EventType   = EET_MOUSE_INPUT_EVENT;
2831                 gui::IGUIElement* root = Environment->getRootGUIElement();
2832
2833                 if (!root) {
2834                         errorstream
2835                         << "GUIFormSpecMenu::preprocessEvent unable to get root element"
2836                         << std::endl;
2837                         return false;
2838                 }
2839                 gui::IGUIElement* hovered = root->getElementFromPoint(
2840                         core::position2d<s32>(
2841                                         event.TouchInput.X,
2842                                         event.TouchInput.Y));
2843
2844                 translated.MouseInput.X = event.TouchInput.X;
2845                 translated.MouseInput.Y = event.TouchInput.Y;
2846                 translated.MouseInput.Control = false;
2847
2848                 bool dont_send_event = false;
2849
2850                 if (event.TouchInput.touchedCount == 1) {
2851                         switch (event.TouchInput.Event) {
2852                                 case ETIE_PRESSED_DOWN:
2853                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2854                                         translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN;
2855                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2856                                         m_down_pos = m_pointer;
2857                                         break;
2858                                 case ETIE_MOVED:
2859                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2860                                         translated.MouseInput.Event = EMIE_MOUSE_MOVED;
2861                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2862                                         break;
2863                                 case ETIE_LEFT_UP:
2864                                         translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP;
2865                                         translated.MouseInput.ButtonStates = 0;
2866                                         hovered = root->getElementFromPoint(m_down_pos);
2867                                         /* we don't have a valid pointer element use last
2868                                          * known pointer pos */
2869                                         translated.MouseInput.X = m_pointer.X;
2870                                         translated.MouseInput.Y = m_pointer.Y;
2871
2872                                         /* reset down pos */
2873                                         m_down_pos = v2s32(0,0);
2874                                         break;
2875                                 default:
2876                                         dont_send_event = true;
2877                                         //this is not supposed to happen
2878                                         errorstream
2879                                         << "GUIFormSpecMenu::preprocessEvent unexpected usecase Event="
2880                                         << event.TouchInput.Event << std::endl;
2881                         }
2882                 } else if ( (event.TouchInput.touchedCount == 2) &&
2883                                 (event.TouchInput.Event == ETIE_PRESSED_DOWN) ) {
2884                         hovered = root->getElementFromPoint(m_down_pos);
2885
2886                         translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
2887                         translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT;
2888                         translated.MouseInput.X = m_pointer.X;
2889                         translated.MouseInput.Y = m_pointer.Y;
2890
2891                         if (hovered) {
2892                                 hovered->OnEvent(translated);
2893                         }
2894
2895                         translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP;
2896                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2897
2898
2899                         if (hovered) {
2900                                 hovered->OnEvent(translated);
2901                         }
2902                         dont_send_event = true;
2903                 }
2904                 /* ignore unhandled 2 touch events ... accidental moving for example */
2905                 else if (event.TouchInput.touchedCount == 2) {
2906                         dont_send_event = true;
2907                 }
2908                 else if (event.TouchInput.touchedCount > 2) {
2909                         errorstream
2910                         << "GUIFormSpecMenu::preprocessEvent to many multitouch events "
2911                         << event.TouchInput.touchedCount << " ignoring them" << std::endl;
2912                 }
2913
2914                 if (dont_send_event) {
2915                         return true;
2916                 }
2917
2918                 /* check if translated event needs to be preprocessed again */
2919                 if (preprocessEvent(translated)) {
2920                         return true;
2921                 }
2922                 if (hovered) {
2923                         grab();
2924                         bool retval = hovered->OnEvent(translated);
2925
2926                         if (event.TouchInput.Event == ETIE_LEFT_UP) {
2927                                 /* reset pointer */
2928                                 m_pointer = v2s32(0,0);
2929                         }
2930                         drop();
2931                         return retval;
2932                 }
2933         }
2934         #endif
2935
2936         return false;
2937 }
2938
2939 /******************************************************************************/
2940 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
2941 {
2942         /* The following code is for capturing double-clicks of the mouse button
2943          * and translating the double-click into an EET_KEY_INPUT_EVENT event
2944          * -- which closes the form -- under some circumstances.
2945          *
2946          * There have been many github issues reporting this as a bug even though it
2947          * was an intended feature.  For this reason, remapping the double-click as
2948          * an ESC must be explicitly set when creating this class via the
2949          * /p remap_dbl_click parameter of the constructor.
2950          */
2951
2952         if (!m_remap_dbl_click)
2953                 return false;
2954
2955         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2956                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
2957                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
2958
2959                 m_doubleclickdetect[1].pos  = m_pointer;
2960                 m_doubleclickdetect[1].time = getTimeMs();
2961         }
2962         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2963                 u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs());
2964                 if (delta > 400) {
2965                         return false;
2966                 }
2967
2968                 double squaredistance =
2969                                 m_doubleclickdetect[0].pos
2970                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
2971
2972                 if (squaredistance > (30*30)) {
2973                         return false;
2974                 }
2975
2976                 SEvent* translated = new SEvent();
2977                 assert(translated != 0);
2978                 //translate doubleclick to escape
2979                 memset(translated, 0, sizeof(SEvent));
2980                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
2981                 translated->KeyInput.Key         = KEY_ESCAPE;
2982                 translated->KeyInput.Control     = false;
2983                 translated->KeyInput.Shift       = false;
2984                 translated->KeyInput.PressedDown = true;
2985                 translated->KeyInput.Char        = 0;
2986                 OnEvent(*translated);
2987
2988                 // no need to send the key up event as we're already deleted
2989                 // and no one else did notice this event
2990                 delete translated;
2991                 return true;
2992         }
2993
2994         return false;
2995 }
2996
2997 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
2998 {
2999         if(event.EventType==EET_KEY_INPUT_EVENT) {
3000                 KeyPress kp(event.KeyInput);
3001                 if (event.KeyInput.PressedDown && ( (kp == EscapeKey) ||
3002                         (kp == getKeySetting("keymap_inventory")) || (kp == CancelKey))) {
3003                         if (m_allowclose) {
3004                                 doPause = false;
3005                                 acceptInput(quit_mode_cancel);
3006                                 quitMenu();
3007                         } else {
3008                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
3009                         }
3010                         return true;
3011                 } else if (m_client != NULL && event.KeyInput.PressedDown &&
3012                         (kp == getKeySetting("keymap_screenshot"))) {
3013                                 m_client->makeScreenshot(m_device);
3014                 }
3015                 if (event.KeyInput.PressedDown &&
3016                         (event.KeyInput.Key==KEY_RETURN ||
3017                          event.KeyInput.Key==KEY_UP ||
3018                          event.KeyInput.Key==KEY_DOWN)
3019                         ) {
3020                         switch (event.KeyInput.Key) {
3021                                 case KEY_RETURN:
3022                                         current_keys_pending.key_enter = true;
3023                                         break;
3024                                 case KEY_UP:
3025                                         current_keys_pending.key_up = true;
3026                                         break;
3027                                 case KEY_DOWN:
3028                                         current_keys_pending.key_down = true;
3029                                         break;
3030                                 break;
3031                                 default:
3032                                         //can't happen at all!
3033                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3034                                         break;
3035                         }
3036                         if (current_keys_pending.key_enter && m_allowclose) {
3037                                 acceptInput(quit_mode_accept);
3038                                 quitMenu();
3039                         } else {
3040                                 acceptInput();
3041                         }
3042                         return true;
3043                 }
3044
3045         }
3046
3047         /* Mouse event other than movement, or crossing the border of inventory
3048           field while holding right mouse button
3049          */
3050         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3051                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3052                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3053                           event.MouseInput.isRightPressed() &&
3054                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3055
3056                 // Get selected item and hovered/clicked item (s)
3057
3058                 m_old_tooltip_id = -1;
3059                 updateSelectedItem();
3060                 ItemSpec s = getItemAtPos(m_pointer);
3061
3062                 Inventory *inv_selected = NULL;
3063                 Inventory *inv_s = NULL;
3064
3065                 if(m_selected_item) {
3066                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3067                         sanity_check(inv_selected);
3068                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3069                 }
3070
3071                 u32 s_count = 0;
3072
3073                 if(s.isValid())
3074                 do { // breakable
3075                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3076
3077                         if(!inv_s) {
3078                                 errorstream<<"InventoryMenu: The selected inventory location "
3079                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
3080                                                 <<std::endl;
3081                                 s.i = -1;  // make it invalid again
3082                                 break;
3083                         }
3084
3085                         InventoryList *list = inv_s->getList(s.listname);
3086                         if(list == NULL) {
3087                                 verbosestream<<"InventoryMenu: The selected inventory list \""
3088                                                 <<s.listname<<"\" does not exist"<<std::endl;
3089                                 s.i = -1;  // make it invalid again
3090                                 break;
3091                         }
3092
3093                         if((u32)s.i >= list->getSize()) {
3094                                 infostream<<"InventoryMenu: The selected inventory list \""
3095                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
3096                                                 <<list->getSize()<<")"<<std::endl;
3097                                 s.i = -1;  // make it invalid again
3098                                 break;
3099                         }
3100
3101                         s_count = list->getItem(s.i).count;
3102                 } while(0);
3103
3104                 bool identical = (m_selected_item != NULL) && s.isValid() &&
3105                         (inv_selected == inv_s) &&
3106                         (m_selected_item->listname == s.listname) &&
3107                         (m_selected_item->i == s.i);
3108
3109                 // buttons: 0 = left, 1 = right, 2 = middle
3110                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event, -1 movement
3111                 int button = 0;
3112                 int updown = 2;
3113                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
3114                         { button = 0; updown = 0; }
3115                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
3116                         { button = 1; updown = 0; }
3117                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
3118                         { button = 2; updown = 0; }
3119                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
3120                         { button = 0; updown = 1; }
3121                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
3122                         { button = 1; updown = 1; }
3123                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
3124                         { button = 2; updown = 1; }
3125                 else if(event.MouseInput.Event == EMIE_MOUSE_MOVED)
3126                         { updown = -1;}
3127
3128                 // Set this number to a positive value to generate a move action
3129                 // from m_selected_item to s.
3130                 u32 move_amount = 0;
3131
3132                 // Set this number to a positive value to generate a drop action
3133                 // from m_selected_item.
3134                 u32 drop_amount = 0;
3135
3136                 // Set this number to a positive value to generate a craft action at s.
3137                 u32 craft_amount = 0;
3138
3139                 if(updown == 0) {
3140                         // Some mouse button has been pressed
3141
3142                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3143                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3144
3145                         m_selected_dragging = false;
3146
3147                         if(s.isValid() && s.listname == "craftpreview") {
3148                                 // Craft preview has been clicked: craft
3149                                 craft_amount = (button == 2 ? 10 : 1);
3150                         }
3151                         else if(m_selected_item == NULL) {
3152                                 if(s_count != 0) {
3153                                         // Non-empty stack has been clicked: select it
3154                                         m_selected_item = new ItemSpec(s);
3155
3156                                         if(button == 1)  // right
3157                                                 m_selected_amount = (s_count + 1) / 2;
3158                                         else if(button == 2)  // middle
3159                                                 m_selected_amount = MYMIN(s_count, 10);
3160                                         else  // left
3161                                                 m_selected_amount = s_count;
3162
3163                                         m_selected_dragging = true;
3164                                         m_rmouse_auto_place = false;
3165                                 }
3166                         }
3167                         else { // m_selected_item != NULL
3168                                 assert(m_selected_amount >= 1);
3169
3170                                 if(s.isValid()) {
3171                                         // Clicked a slot: move
3172                                         if(button == 1)  // right
3173                                                 move_amount = 1;
3174                                         else if(button == 2)  // middle
3175                                                 move_amount = MYMIN(m_selected_amount, 10);
3176                                         else  // left
3177                                                 move_amount = m_selected_amount;
3178
3179                                         if(identical) {
3180                                                 if(move_amount >= m_selected_amount)
3181                                                         m_selected_amount = 0;
3182                                                 else
3183                                                         m_selected_amount -= move_amount;
3184                                                 move_amount = 0;
3185                                         }
3186                                 }
3187                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3188                                         // Clicked outside of the window: drop
3189                                         if(button == 1)  // right
3190                                                 drop_amount = 1;
3191                                         else if(button == 2)  // middle
3192                                                 drop_amount = MYMIN(m_selected_amount, 10);
3193                                         else  // left
3194                                                 drop_amount = m_selected_amount;
3195                                 }
3196                         }
3197                 }
3198                 else if(updown == 1) {
3199                         // Some mouse button has been released
3200
3201                         //infostream<<"Mouse button "<<button<<" released at p=("
3202                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3203
3204                         if(m_selected_item != NULL && m_selected_dragging && s.isValid()) {
3205                                 if(!identical) {
3206                                         // Dragged to different slot: move all selected
3207                                         move_amount = m_selected_amount;
3208                                 }
3209                         }
3210                         else if(m_selected_item != NULL && m_selected_dragging &&
3211                                 !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
3212                                 // Dragged outside of window: drop all selected
3213                                 drop_amount = m_selected_amount;
3214                         }
3215
3216                         m_selected_dragging = false;
3217                         // Keep count of how many times right mouse button has been
3218                         // clicked. One click is drag without dropping. Click + release
3219                         // + click changes to drop one item when moved mode
3220                         if(button == 1 && m_selected_item != NULL)
3221                                 m_rmouse_auto_place = !m_rmouse_auto_place;
3222                 }
3223                 else if(updown == -1) {
3224                         // Mouse has been moved and rmb is down and mouse pointer just
3225                         // entered a new inventory field (checked in the entry-if, this
3226                         // is the only action here that is generated by mouse movement)
3227                         if(m_selected_item != NULL && s.isValid()){
3228                                 // Move 1 item
3229                                 // TODO: middle mouse to move 10 items might be handy
3230                                 if (m_rmouse_auto_place) {
3231                                         // Only move an item if the destination slot is empty
3232                                         // or contains the same item type as what is going to be
3233                                         // moved
3234                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3235                                         InventoryList *list_to = inv_s->getList(s.listname);
3236                                         assert(list_from && list_to);
3237                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3238                                         ItemStack stack_to = list_to->getItem(s.i);
3239                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3240                                                 move_amount = 1;
3241                                 }
3242                         }
3243                 }
3244
3245                 // Possibly send inventory action to server
3246                 if(move_amount > 0)
3247                 {
3248                         // Send IACTION_MOVE
3249
3250                         assert(m_selected_item && m_selected_item->isValid());
3251                         assert(s.isValid());
3252
3253                         assert(inv_selected && inv_s);
3254                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3255                         InventoryList *list_to = inv_s->getList(s.listname);
3256                         assert(list_from && list_to);
3257                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3258                         ItemStack stack_to = list_to->getItem(s.i);
3259
3260                         // Check how many items can be moved
3261                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3262                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
3263                         // If source stack cannot be added to destination stack at all,
3264                         // they are swapped
3265                         if ((leftover.count == stack_from.count) &&
3266                                         (leftover.name == stack_from.name)) {
3267                                 m_selected_amount = stack_to.count;
3268                                 // In case the server doesn't directly swap them but instead
3269                                 // moves stack_to somewhere else, set this
3270                                 m_selected_content_guess = stack_to;
3271                                 m_selected_content_guess_inventory = s.inventoryloc;
3272                         }
3273                         // Source stack goes fully into destination stack
3274                         else if(leftover.empty()) {
3275                                 m_selected_amount -= move_amount;
3276                                 m_selected_content_guess = ItemStack(); // Clear
3277                         }
3278                         // Source stack goes partly into destination stack
3279                         else {
3280                                 move_amount -= leftover.count;
3281                                 m_selected_amount -= move_amount;
3282                                 m_selected_content_guess = ItemStack(); // Clear
3283                         }
3284
3285                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
3286                         IMoveAction *a = new IMoveAction();
3287                         a->count = move_amount;
3288                         a->from_inv = m_selected_item->inventoryloc;
3289                         a->from_list = m_selected_item->listname;
3290                         a->from_i = m_selected_item->i;
3291                         a->to_inv = s.inventoryloc;
3292                         a->to_list = s.listname;
3293                         a->to_i = s.i;
3294                         m_invmgr->inventoryAction(a);
3295                 }
3296                 else if(drop_amount > 0) {
3297                         m_selected_content_guess = ItemStack(); // Clear
3298
3299                         // Send IACTION_DROP
3300
3301                         assert(m_selected_item && m_selected_item->isValid());
3302                         assert(inv_selected);
3303                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3304                         assert(list_from);
3305                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3306
3307                         // Check how many items can be dropped
3308                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3309                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3310                         m_selected_amount -= drop_amount;
3311
3312                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
3313                         IDropAction *a = new IDropAction();
3314                         a->count = drop_amount;
3315                         a->from_inv = m_selected_item->inventoryloc;
3316                         a->from_list = m_selected_item->listname;
3317                         a->from_i = m_selected_item->i;
3318                         m_invmgr->inventoryAction(a);
3319                 }
3320                 else if(craft_amount > 0) {
3321                         m_selected_content_guess = ItemStack(); // Clear
3322
3323                         // Send IACTION_CRAFT
3324
3325                         assert(s.isValid());
3326                         assert(inv_s);
3327
3328                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
3329                         ICraftAction *a = new ICraftAction();
3330                         a->count = craft_amount;
3331                         a->craft_inv = s.inventoryloc;
3332                         m_invmgr->inventoryAction(a);
3333                 }
3334
3335                 // If m_selected_amount has been decreased to zero, deselect
3336                 if(m_selected_amount == 0) {
3337                         delete m_selected_item;
3338                         m_selected_item = NULL;
3339                         m_selected_amount = 0;
3340                         m_selected_dragging = false;
3341                         m_selected_content_guess = ItemStack();
3342                 }
3343                 m_old_pointer = m_pointer;
3344         }
3345         if(event.EventType==EET_GUI_EVENT) {
3346
3347                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
3348                                 && isVisible()) {
3349                         // find the element that was clicked
3350                         for(unsigned int i=0; i<m_fields.size(); i++) {
3351                                 FieldSpec &s = m_fields[i];
3352                                 if ((s.ftype == f_TabHeader) &&
3353                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3354                                         s.send = true;
3355                                         acceptInput();
3356                                         s.send = false;
3357                                         return true;
3358                                 }
3359                         }
3360                 }
3361                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
3362                                 && isVisible()) {
3363                         if(!canTakeFocus(event.GUIEvent.Element)) {
3364                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
3365                                                 <<std::endl;
3366                                 // Returning true disables focus change
3367                                 return true;
3368                         }
3369                 }
3370                 if((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
3371                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
3372                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
3373                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
3374                         unsigned int btn_id = event.GUIEvent.Caller->getID();
3375
3376                         if (btn_id == 257) {
3377                                 if (m_allowclose) {
3378                                         acceptInput(quit_mode_accept);
3379                                         quitMenu();
3380                                 } else {
3381                                         acceptInput();
3382                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3383                                 }
3384                                 // quitMenu deallocates menu
3385                                 return true;
3386                         }
3387
3388                         // find the element that was clicked
3389                         for(u32 i=0; i<m_fields.size(); i++) {
3390                                 FieldSpec &s = m_fields[i];
3391                                 // if its a button, set the send field so
3392                                 // lua knows which button was pressed
3393                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
3394                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3395                                         s.send = true;
3396                                         if(s.is_exit) {
3397                                                 if (m_allowclose) {
3398                                                         acceptInput(quit_mode_accept);
3399                                                         quitMenu();
3400                                                 } else {
3401                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3402                                                 }
3403                                                 return true;
3404                                         } else {
3405                                                 acceptInput(quit_mode_no);
3406                                                 s.send = false;
3407                                                 return true;
3408                                         }
3409                                 }
3410                                 else if ((s.ftype == f_DropDown) &&
3411                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3412                                         // only send the changed dropdown
3413                                         for(u32 i=0; i<m_fields.size(); i++) {
3414                                                 FieldSpec &s2 = m_fields[i];
3415                                                 if (s2.ftype == f_DropDown) {
3416                                                         s2.send = false;
3417                                                 }
3418                                         }
3419                                         s.send = true;
3420                                         acceptInput(quit_mode_no);
3421
3422                                         // revert configuration to make sure dropdowns are sent on
3423                                         // regular button click
3424                                         for(u32 i=0; i<m_fields.size(); i++) {
3425                                                 FieldSpec &s2 = m_fields[i];
3426                                                 if (s2.ftype == f_DropDown) {
3427                                                         s2.send = true;
3428                                                 }
3429                                         }
3430                                         return true;
3431                                 }
3432                                 else if ((s.ftype == f_ScrollBar) &&
3433                                         (s.fid == event.GUIEvent.Caller->getID()))
3434                                 {
3435                                         s.fdefault = L"Changed";
3436                                         acceptInput(quit_mode_no);
3437                                         s.fdefault = L"";
3438                                 }
3439                         }
3440                 }
3441
3442                 if(event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
3443                         if(event.GUIEvent.Caller->getID() > 257) {
3444
3445                                 if (m_allowclose) {
3446                                         acceptInput(quit_mode_accept);
3447                                         quitMenu();
3448                                 } else {
3449                                         current_keys_pending.key_enter = true;
3450                                         acceptInput();
3451                                 }
3452                                 // quitMenu deallocates menu
3453                                 return true;
3454                         }
3455                 }
3456
3457                 if(event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
3458                         int current_id = event.GUIEvent.Caller->getID();
3459                         if(current_id > 257) {
3460                                 // find the element that was clicked
3461                                 for(u32 i=0; i<m_fields.size(); i++) {
3462                                         FieldSpec &s = m_fields[i];
3463                                         // if it's a table, set the send field
3464                                         // so lua knows which table was changed
3465                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
3466                                                 s.send = true;
3467                                                 acceptInput();
3468                                                 s.send=false;
3469                                         }
3470                                 }
3471                                 return true;
3472                         }
3473                 }
3474         }
3475
3476         return Parent ? Parent->OnEvent(event) : false;
3477 }
3478
3479 /**
3480  * get name of element by element id
3481  * @param id of element
3482  * @return name string or empty string
3483  */
3484 std::wstring GUIFormSpecMenu::getNameByID(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->fname;
3490                 }
3491         }
3492         return L"";
3493 }
3494
3495 /**
3496  * get label of element by id
3497  * @param id of element
3498  * @return label string or empty string
3499  */
3500 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
3501 {
3502         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3503                                 iter != m_fields.end(); iter++) {
3504                 if (iter->fid == id) {
3505                         return iter->flabel;
3506                 }
3507         }
3508         return L"";
3509 }