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