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