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