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