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