Add translation for main menu
[oweals/minetest.git] / src / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <sstream>
25 #include <limits>
26 #include "guiFormSpecMenu.h"
27 #include "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 #include "gettime.h"
47 #include "gettext.h"
48
49 #define MY_CHECKPOS(a,b)                                                                                                        \
50         if (v_pos.size() != 2) {                                                                                                \
51                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
52                         << parts[b] << "\"" << std::endl;                                                               \
53                         return;                                                                                                                 \
54         }
55
56 #define MY_CHECKGEOM(a,b)                                                                                                       \
57         if (v_geom.size() != 2) {                                                                                               \
58                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
59                         << parts[b] << "\"" << std::endl;                                                               \
60                         return;                                                                                                                 \
61         }
62
63
64 /*
65         GUIFormSpecMenu
66 */
67
68 GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev,
69                 gui::IGUIElement* parent, s32 id,
70                 IMenuManager *menumgr,
71                 InventoryManager *invmgr,
72                 IGameDef *gamedef
73 ):
74         GUIModalMenu(dev->getGUIEnvironment(), parent, id, menumgr),
75         m_device(dev),
76         m_invmgr(invmgr),
77         m_gamedef(gamedef),
78         m_form_src(NULL),
79         m_text_dst(NULL),
80         m_selected_item(NULL),
81         m_selected_amount(0),
82         m_selected_dragging(false),
83         m_listbox_click_fname(),
84         m_listbox_click_index(-1),
85         m_listbox_click_time(0),
86         m_listbox_doubleclick(false),
87         m_tooltip_element(NULL),
88         m_allowclose(true),
89         m_lock(false)
90 {
91         current_keys_pending.key_down = false;
92         current_keys_pending.key_up = false;
93         current_keys_pending.key_enter = false;
94         current_keys_pending.key_escape = false;
95
96 }
97
98 GUIFormSpecMenu::~GUIFormSpecMenu()
99 {
100         removeChildren();
101
102         delete m_selected_item;
103         delete m_form_src;
104         delete m_text_dst;
105 }
106
107 void GUIFormSpecMenu::removeChildren()
108 {
109         const core::list<gui::IGUIElement*> &children = getChildren();
110         core::list<gui::IGUIElement*> children_copy;
111         for(core::list<gui::IGUIElement*>::ConstIterator
112                         i = children.begin(); i != children.end(); i++)
113         {
114                 children_copy.push_back(*i);
115         }
116         for(core::list<gui::IGUIElement*>::Iterator
117                         i = children_copy.begin();
118                         i != children_copy.end(); i++)
119         {
120                 (*i)->remove();
121         }
122         /*{
123                 gui::IGUIElement *e = getElementFromId(256);
124                 if(e != NULL)
125                         e->remove();
126         }*/
127         if(m_tooltip_element)
128         {
129                 m_tooltip_element->remove();
130                 m_tooltip_element = NULL;
131         }
132 }
133
134 int GUIFormSpecMenu::getListboxIndex(std::string listboxname) {
135
136         std::wstring wlistboxname = narrow_to_wide(listboxname.c_str());
137
138         for(unsigned int i=0; i < m_listboxes.size(); i++) {
139
140                 std::wstring name(m_listboxes[i].first.fname.c_str());
141                 if ( name == wlistboxname) {
142                         return m_listboxes[i].second->getSelected();
143                 }
144         }
145         return -1;
146 }
147
148 bool GUIFormSpecMenu::checkListboxClick(std::wstring wlistboxname,
149                 int eventtype)
150 {
151         // WARNING: BLACK IRRLICHT MAGIC
152         // Used to fix Irrlicht's subpar reporting of single clicks and double
153         // clicks in listboxes (gui::EGET_LISTBOX_CHANGED,
154         // gui::EGET_LISTBOX_SELECTED_AGAIN):
155         // 1. IGUIListBox::setSelected() is counted as a click.
156         //    Including the initial setSelected() done by parseTextList().
157         // 2. Clicking on a the selected item and then dragging for less
158         //    than 500ms is counted as a doubleclick, no matter when the
159         //    item was previously selected (e.g. more than 500ms ago)
160
161         // So when Irrlicht reports a doubleclick, we need to check
162         // for ourselves if really was a doubleclick. Or just a fake.
163
164         for(unsigned int i=0; i < m_listboxes.size(); i++) {
165                 std::wstring name(m_listboxes[i].first.fname.c_str());
166                 int selected = m_listboxes[i].second->getSelected();
167                 if (name == wlistboxname && selected >= 0) {
168                         u32 now = getTimeMs();
169                         bool doubleclick =
170                                 (eventtype == gui::EGET_LISTBOX_SELECTED_AGAIN)
171                                 && (name == m_listbox_click_fname)
172                                 && (selected == m_listbox_click_index)
173                                 && (m_listbox_click_time >= now - 500);
174                         m_listbox_click_fname = name;
175                         m_listbox_click_index = selected;
176                         m_listbox_click_time = now;
177                         m_listbox_doubleclick = doubleclick;
178                         return true;
179                 }
180         }
181         return false;
182 }
183
184 gui::IGUIScrollBar* GUIFormSpecMenu::getListboxScrollbar(
185                 gui::IGUIListBox *listbox)
186 {
187         // WARNING: BLACK IRRLICHT MAGIC
188         // Ordinarily, due to how formspecs work (recreating the entire GUI
189         // when something changes), when you select an item in a textlist
190         // with more items than fit in the visible area, the newly selected
191         // item is scrolled to the bottom of the visible area. This is
192         // annoying and breaks GUI designs that use double clicks.
193
194         // This function helps fixing this problem by giving direct access
195         // to a listbox's scrollbar. This works because CGUIListBox doesn't
196         // cache the scrollbar position anywhere.
197
198         // If this stops working in a future irrlicht version, consider
199         // maintaining a local copy of irr::gui::CGUIListBox, possibly also
200         // fixing the other reasons why black irrlicht magic is needed.
201
202         core::list<gui::IGUIElement*> children = listbox->getChildren();
203         for(core::list<gui::IGUIElement*>::Iterator it = children.begin();
204                         it != children.end(); ++it) {
205                 gui::IGUIElement* child = *it;
206                 if (child && child->getType() == gui::EGUIET_SCROLL_BAR) {
207                         return static_cast<gui::IGUIScrollBar*>(child);
208                 }
209         }
210
211         verbosestream<<"getListboxScrollbar: WARNING: "
212                         <<"listbox has no scrollbar"<<std::endl;
213         return NULL;
214 }
215
216 std::vector<std::string> split(const std::string &s, char delim) {
217         std::vector<std::string> tokens;
218
219         std::string current = "";
220         bool last_was_escape = false;
221         for(unsigned int i=0; i < s.size(); i++) {
222                 if (last_was_escape) {
223                         current += '\\';
224                         current += s.c_str()[i];
225                         last_was_escape = false;
226                 }
227                 else {
228                         if (s.c_str()[i] == delim) {
229                                 tokens.push_back(current);
230                                 current = "";
231                                 last_was_escape = false;
232                         }
233                         else if (s.c_str()[i] == '\\'){
234                                 last_was_escape = true;
235                         }
236                         else {
237                                 current += s.c_str()[i];
238                                 last_was_escape = false;
239                         }
240                 }
241         }
242         //push last element
243         tokens.push_back(current);
244
245         return tokens;
246 }
247
248 void GUIFormSpecMenu::parseSize(parserData* data,std::string element) {
249         std::vector<std::string> parts = split(element,',');
250
251         if (parts.size() == 2) {
252                 v2f invsize;
253
254                 if (parts[1].find(';') != std::string::npos)
255                         parts[1] = parts[1].substr(0,parts[1].find(';'));
256
257                 invsize.X = stof(parts[0]);
258                 invsize.Y = stof(parts[1]);
259
260                 if (m_lock) {
261                         v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize();
262                         v2u32 delta = current_screensize - m_lockscreensize;
263
264                         if (current_screensize.Y > m_lockscreensize.Y)
265                                 delta.Y /= 2;
266                         else
267                                 delta.Y = 0;
268
269                         if (current_screensize.X > m_lockscreensize.X)
270                                 delta.X /= 2;
271                         else
272                                 delta.X = 0;
273
274                         offset = v2s32(delta.X,delta.Y);
275
276                         data->screensize = m_lockscreensize;
277                 }
278                 else {
279                         offset = v2s32(0,0);
280                 }
281
282                 padding = v2s32(data->screensize.Y/40, data->screensize.Y/40);
283                 spacing = v2s32(data->screensize.Y/12, data->screensize.Y/13);
284                 imgsize = v2s32(data->screensize.Y/15, data->screensize.Y/15);
285                 data->size = v2s32(
286                         padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
287                         padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + (data->helptext_h-5)
288                 );
289                 data->rect = core::rect<s32>(
290                                 data->screensize.X/2 - data->size.X/2 + offset.X,
291                                 data->screensize.Y/2 - data->size.Y/2 + offset.Y,
292                                 data->screensize.X/2 + data->size.X/2 + offset.X,
293                                 data->screensize.Y/2 + data->size.Y/2 + offset.Y
294                 );
295
296                 DesiredRect = data->rect;
297                 recalculateAbsolutePosition(false);
298                 data->basepos = getBasePos();
299                 data->bp_set = 2;
300                 return;
301         }
302         errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'"  << std::endl;
303 }
304
305 void GUIFormSpecMenu::parseList(parserData* data,std::string element) {
306
307         if (m_gamedef == 0) {
308                 errorstream<<"WARNING: invalid use of 'list' with m_gamedef==0"<<std::endl;
309                 return;
310         }
311
312         std::vector<std::string> parts = split(element,';');
313
314         if ((parts.size() == 4) || (parts.size() == 5)) {
315                 std::string location = parts[0];
316                 std::string listname = parts[1];
317                 std::vector<std::string> v_pos  = split(parts[2],',');
318                 std::vector<std::string> v_geom = split(parts[3],',');
319                 std::string startindex = "";
320                 if (parts.size() == 5)
321                         startindex = parts[4];
322
323                 MY_CHECKPOS("list",2);
324                 MY_CHECKGEOM("list",3);
325
326                 InventoryLocation loc;
327
328                 if(location == "context" || location == "current_name")
329                         loc = m_current_inventory_location;
330                 else
331                         loc.deSerialize(location);
332
333                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
334                 pos.X += stof(v_pos[0]) * (float)spacing.X;
335                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
336
337                 v2s32 geom;
338                 geom.X = stoi(v_geom[0]);
339                 geom.Y = stoi(v_geom[1]);
340
341                 s32 start_i = 0;
342                 if(startindex != "")
343                         start_i = stoi(startindex);
344                 if(data->bp_set != 2)
345                         errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
346                 m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
347                 return;
348         }
349         errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
350 }
351
352 void GUIFormSpecMenu::parseCheckbox(parserData* data,std::string element) {
353         std::vector<std::string> parts = split(element,';');
354
355         if ((parts.size() == 3) || (parts.size() == 4)) {
356                 std::vector<std::string> v_pos = split(parts[0],',');
357                 std::string name = parts[1];
358                 std::string label = parts[2];
359                 std::string selected = "";
360
361                 if (parts.size() == 4)
362                         selected = parts[3];
363
364                 MY_CHECKPOS("checkbox",0);
365
366                 v2s32 pos = padding;
367                 pos.X += stof(v_pos[0]) * (float) spacing.X;
368                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
369
370                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
371
372                 bool fselected = false;
373
374                 if (selected == "true")
375                         fselected = true;
376
377                 std::wstring wlabel = narrow_to_wide(label.c_str());
378
379                 FieldSpec spec = FieldSpec(
380                                 narrow_to_wide(name.c_str()),
381                                 L"",
382                                 wlabel,
383                                 258+m_fields.size()
384                         );
385
386                 spec.ftype = f_CheckBox;
387                 spec.flabel = wlabel; //Needed for displaying text on MSVC
388                 gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this,
389                                         spec.fid, spec.flabel.c_str());
390                 m_checkboxes.push_back(std::pair<FieldSpec,gui::IGUICheckBox*>(spec,e));
391                 m_fields.push_back(spec);
392                 return;
393         }
394         errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
395 }
396
397 void GUIFormSpecMenu::parseImage(parserData* data,std::string element) {
398         std::vector<std::string> parts = split(element,';');
399
400         if (parts.size() == 3) {
401                 std::vector<std::string> v_pos = split(parts[0],',');
402                 std::vector<std::string> v_geom = split(parts[1],',');
403                 std::string name = parts[2];
404
405                 MY_CHECKPOS("image",0);
406                 MY_CHECKGEOM("image",1);
407
408                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
409                 pos.X += stof(v_pos[0]) * (float) spacing.X;
410                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
411
412                 v2s32 geom;
413                 geom.X = stoi(v_geom[0]) * (float)imgsize.X;
414                 geom.Y = stoi(v_geom[1]) * (float)imgsize.Y;
415
416                 if(data->bp_set != 2)
417                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
418                 m_images.push_back(ImageDrawSpec(name, pos, geom));
419                 return;
420         }
421
422         if (parts.size() == 2) {
423                 std::vector<std::string> v_pos = split(parts[0],',');
424                 std::string name = parts[1];
425
426                 MY_CHECKPOS("image",0);
427
428                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
429                 pos.X += stof(v_pos[0]) * (float) spacing.X;
430                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
431
432                 if(data->bp_set != 2)
433                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
434                 m_images.push_back(ImageDrawSpec(name, pos));
435                 return;
436         }
437         errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
438 }
439
440 void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element) {
441         std::vector<std::string> parts = split(element,';');
442
443         if (parts.size() == 3) {
444                 std::vector<std::string> v_pos = split(parts[0],',');
445                 std::vector<std::string> v_geom = split(parts[1],',');
446                 std::string name = parts[2];
447
448                 MY_CHECKPOS("itemimage",0);
449                 MY_CHECKGEOM("itemimage",1);
450
451                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
452                 pos.X += stof(v_pos[0]) * (float) spacing.X;
453                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
454
455                 v2s32 geom;
456                 geom.X = stoi(v_geom[0]) * (float)imgsize.X;
457                 geom.Y = stoi(v_geom[1]) * (float)imgsize.Y;
458
459                 if(data->bp_set != 2)
460                         errorstream<<"WARNING: invalid use of item_image without a size[] element"<<std::endl;
461                 m_itemimages.push_back(ImageDrawSpec(name, pos, geom));
462                 return;
463         }
464         errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
465 }
466
467 void GUIFormSpecMenu::parseButton(parserData* data,std::string element,std::string type) {
468         std::vector<std::string> parts = split(element,';');
469
470         if (parts.size() == 4) {
471                 std::vector<std::string> v_pos = split(parts[0],',');
472                 std::vector<std::string> v_geom = split(parts[1],',');
473                 std::string name = parts[2];
474                 std::string label = parts[3];
475
476                 MY_CHECKPOS("button",0);
477                 MY_CHECKGEOM("button",1);
478
479                 v2s32 pos = padding;
480                 pos.X += stof(v_pos[0]) * (float)spacing.X;
481                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
482
483                 v2s32 geom;
484                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
485                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
486
487                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
488
489                 if(data->bp_set != 2)
490                         errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
491
492                 label = unescape_string(label);
493
494                 std::wstring wlabel = narrow_to_wide(label.c_str());
495
496                 FieldSpec spec = FieldSpec(
497                         narrow_to_wide(name.c_str()),
498                         wlabel,
499                         L"",
500                         258+m_fields.size()
501                 );
502                 spec.ftype = f_Button;
503                 if(type == "button_exit")
504                         spec.is_exit = true;
505
506                 Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
507                 m_fields.push_back(spec);
508                 return;
509         }
510         errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
511 }
512
513 void GUIFormSpecMenu::parseBackground(parserData* data,std::string element) {
514         std::vector<std::string> parts = split(element,';');
515
516         if (parts.size() == 3) {
517                 std::vector<std::string> v_pos = split(parts[0],',');
518                 std::vector<std::string> v_geom = split(parts[1],',');
519                 std::string name = parts[2];
520
521                 MY_CHECKPOS("background",0);
522                 MY_CHECKGEOM("background",1);
523
524                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
525                 pos.X += stof(v_pos[0]) * (float)spacing.X - ((float)spacing.X-(float)imgsize.X)/2;
526                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - ((float)spacing.Y-(float)imgsize.Y)/2;
527
528                 v2s32 geom;
529                 geom.X = stof(v_geom[0]) * (float)spacing.X;
530                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
531
532                 if(data->bp_set != 2)
533                         errorstream<<"WARNING: invalid use of background without a size[] element"<<std::endl;
534                 m_backgrounds.push_back(ImageDrawSpec(name, pos, geom));
535                 return;
536         }
537         errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
538 }
539
540 void GUIFormSpecMenu::parseTextList(parserData* data,std::string element) {
541         std::vector<std::string> parts = split(element,';');
542
543         if ((parts.size() == 5) || (parts.size() == 6)) {
544                 std::vector<std::string> v_pos = split(parts[0],',');
545                 std::vector<std::string> v_geom = split(parts[1],',');
546                 std::string name = parts[2];
547                 std::vector<std::string> items = split(parts[3],',');
548                 std::string str_initial_selection = "";
549                 std::string str_transparent = "false";
550
551                 if (parts.size() >= 5)
552                         str_initial_selection = parts[4];
553
554                 if (parts.size() >= 6)
555                         str_transparent = parts[5];
556
557                 MY_CHECKPOS("textlist",0);
558                 MY_CHECKGEOM("textlist",1);
559
560                 v2s32 pos = padding;
561                 pos.X += stof(v_pos[0]) * (float)spacing.X;
562                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
563
564                 v2s32 geom;
565                 geom.X = stof(v_geom[0]) * (float)spacing.X;
566                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
567
568
569                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
570
571                 std::wstring fname_w = narrow_to_wide(name.c_str());
572
573                 FieldSpec spec = FieldSpec(
574                         fname_w,
575                         L"",
576                         L"",
577                         258+m_fields.size()
578                 );
579
580                 spec.ftype = f_ListBox;
581
582                 //now really show list
583                 gui::IGUIListBox *e = Environment->addListBox(rect, this,spec.fid);
584
585                 //don't reset if we already have a user specified selection
586                 if (data->listbox_selections.find(fname_w) == data->listbox_selections.end()) {
587                         e->setAutoScrollEnabled(false);
588                 }
589
590                 if (str_transparent == "false")
591                         e->setDrawBackground(true);
592
593                 for (unsigned int i=0; i < items.size(); i++) {
594                         if (items[i].c_str()[0] == '#') {
595                                 if (items[i].c_str()[1] == '#') {
596                                         e->addItem(narrow_to_wide(unescape_string(items[i])).c_str() +1);
597                                 }
598                                 else {
599                                         std::string color = items[i].substr(1,6);
600                                         std::wstring toadd =
601                                                 narrow_to_wide(unescape_string(items[i]).c_str() + 7);
602
603                                         e->addItem(toadd.c_str());
604
605                                         irr::video::SColor toset;
606
607                                         if (parseColor(color, toset))
608                                                 e->setItemOverrideColor(i,toset);
609                                 }
610                         }
611                         else {
612                                 e->addItem(narrow_to_wide(unescape_string(items[i])).c_str());
613                         }
614                 }
615
616                 if (data->listbox_selections.find(fname_w) != data->listbox_selections.end()) {
617                         e->setSelected(data->listbox_selections[fname_w]);
618                 }
619
620                 if (data->listbox_scroll.find(fname_w) != data->listbox_scroll.end()) {
621                         gui::IGUIScrollBar *scrollbar = getListboxScrollbar(e);
622                         if (scrollbar) {
623                                 scrollbar->setPos(data->listbox_scroll[fname_w]);
624                         }
625                 }
626
627                 if (str_initial_selection != "")
628                         e->setSelected(stoi(str_initial_selection.c_str())-1);
629
630                 m_listboxes.push_back(std::pair<FieldSpec,gui::IGUIListBox*>(spec,e));
631                 m_fields.push_back(spec);
632                 return;
633         }
634         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
635 }
636
637
638 void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element) {
639         std::vector<std::string> parts = split(element,';');
640
641         if (parts.size() == 5) {
642                 std::vector<std::string> v_pos = split(parts[0],',');
643                 std::string name = parts[2];
644                 std::vector<std::string> items = split(parts[3],',');
645                 std::string str_initial_selection = "";
646                 str_initial_selection = parts[4];
647
648                 MY_CHECKPOS("dropdown",0);
649
650                 v2s32 pos = padding;
651                 pos.X += stof(v_pos[0]) * (float)spacing.X;
652                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
653
654                 s32 width = stof(parts[1]) * (float)spacing.Y;
655
656                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+width, pos.Y+30);
657
658                 std::wstring fname_w = narrow_to_wide(name.c_str());
659
660                 FieldSpec spec = FieldSpec(
661                         fname_w,
662                         L"",
663                         L"",
664                         258+m_fields.size()
665                 );
666
667                 spec.ftype = f_DropDown;
668                 spec.send = true;
669
670                 //now really show list
671                 gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
672
673                 //don't reset if we already have a user specified selection
674                 //if (data->combobox_selections.find(fname_w) == data->listbox_selections.end()) {
675                 //      e->setAutoScrollEnabled(false);
676                 //}
677
678                 for (unsigned int i=0; i < items.size(); i++) {
679                         e->addItem(narrow_to_wide(items[i]).c_str());
680                 }
681
682                 if (str_initial_selection != "")
683                         e->setSelected(stoi(str_initial_selection.c_str())-1);
684
685                 //if (data->listbox_selections.find(fname_w) != data->listbox_selections.end()) {
686                 //      e->setSelected(data->listbox_selections[fname_w]);
687                 //}
688
689                 //m_listboxes.push_back(std::pair<FieldSpec,gui::IGUIListBox*>(spec,e));
690                 m_fields.push_back(spec);
691                 return;
692         }
693         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
694                                 << element << "'"  << std::endl;
695 }
696
697 void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element) {
698         std::vector<std::string> parts = split(element,';');
699
700         if (parts.size() == 4) {
701                 std::vector<std::string> v_pos = split(parts[0],',');
702                 std::vector<std::string> v_geom = split(parts[1],',');
703                 std::string name = parts[2];
704                 std::string label = parts[3];
705
706                 MY_CHECKPOS("pwdfield",0);
707                 MY_CHECKGEOM("pwdfield",1);
708
709                 v2s32 pos;
710                 pos.X += stof(v_pos[0]) * (float)spacing.X;
711                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
712
713                 v2s32 geom;
714                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
715
716                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
717                 pos.Y -= 15;
718                 geom.Y = 30;
719
720                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
721
722                 label = unescape_string(label);
723
724                 std::wstring wlabel = narrow_to_wide(label.c_str());
725
726                 FieldSpec spec = FieldSpec(
727                         narrow_to_wide(name.c_str()),
728                         wlabel,
729                         L"",
730                         258+m_fields.size()
731                         );
732
733                 spec.send = true;
734                 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
735                 Environment->setFocus(e);
736
737                 if (label.length() > 1)
738                 {
739                         rect.UpperLeftCorner.Y -= 15;
740                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
741                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
742                 }
743
744                 e->setPasswordBox(true,L'*');
745
746                 irr::SEvent evt;
747                 evt.EventType            = EET_KEY_INPUT_EVENT;
748                 evt.KeyInput.Key         = KEY_END;
749                 evt.KeyInput.Char        = 0;
750                 evt.KeyInput.Control     = 0;
751                 evt.KeyInput.Shift       = 0;
752                 evt.KeyInput.PressedDown = true;
753                 e->OnEvent(evt);
754                 m_fields.push_back(spec);
755                 return;
756         }
757         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
758 }
759
760 void GUIFormSpecMenu::parseSimpleField(parserData* data,std::vector<std::string> &parts) {
761         std::string name = parts[0];
762         std::string label = parts[1];
763         std::string default_val = parts[2];
764
765         core::rect<s32> rect;
766
767         if(!data->bp_set)
768         {
769                 rect = core::rect<s32>(
770                         data->screensize.X/2 - 580/2,
771                         data->screensize.Y/2 - 300/2,
772                         data->screensize.X/2 + 580/2,
773                         data->screensize.Y/2 + 300/2
774                 );
775                 DesiredRect = rect;
776                 recalculateAbsolutePosition(false);
777                 data->basepos = getBasePos();
778                 data->bp_set = 1;
779         }
780         else if(data->bp_set == 2)
781                 errorstream<<"WARNING: invalid use of unpositioned \"field\" in inventory"<<std::endl;
782
783         v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
784         pos.Y = ((m_fields.size()+2)*60);
785         v2s32 size = DesiredRect.getSize();
786
787         rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
788
789
790         if(m_form_src)
791                 default_val = m_form_src->resolveText(default_val);
792
793         default_val = unescape_string(default_val);
794         label = unescape_string(label);
795
796         std::wstring wlabel = narrow_to_wide(label.c_str());
797
798         FieldSpec spec = FieldSpec(
799                 narrow_to_wide(name.c_str()),
800                 wlabel,
801                 narrow_to_wide(default_val.c_str()),
802                 258+m_fields.size()
803         );
804
805         if (name == "")
806         {
807                 // spec field id to 0, this stops submit searching for a value that isn't there
808                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
809         }
810         else
811         {
812                 spec.send = true;
813                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
814                 Environment->setFocus(e);
815
816                 irr::SEvent evt;
817                 evt.EventType            = EET_KEY_INPUT_EVENT;
818                 evt.KeyInput.Key         = KEY_END;
819                 evt.KeyInput.Char        = 0;
820                 evt.KeyInput.Control     = 0;
821                 evt.KeyInput.Shift       = 0;
822                 evt.KeyInput.PressedDown = true;
823                 e->OnEvent(evt);
824
825                 if (label.length() > 1)
826                 {
827                         rect.UpperLeftCorner.Y -= 15;
828                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
829                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
830                 }
831         }
832
833         m_fields.push_back(spec);
834 }
835
836 void GUIFormSpecMenu::parseTextArea(parserData* data,std::vector<std::string>& parts,std::string type) {
837
838         std::vector<std::string> v_pos = split(parts[0],',');
839         std::vector<std::string> v_geom = split(parts[1],',');
840         std::string name = parts[2];
841         std::string label = parts[3];
842         std::string default_val = parts[4];
843
844         MY_CHECKPOS(type,0);
845         MY_CHECKGEOM(type,1);
846
847         v2s32 pos;
848         pos.X = stof(v_pos[0]) * (float) spacing.X;
849         pos.Y = stof(v_pos[1]) * (float) spacing.Y;
850
851         v2s32 geom;
852
853         geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
854
855         if (type == "textarea")
856         {
857                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
858                 pos.Y += 15;
859         }
860         else
861         {
862                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
863                 pos.Y -= 15;
864                 geom.Y = 30;
865         }
866
867         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
868
869         if(data->bp_set != 2)
870                 errorstream<<"WARNING: invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
871
872         if(m_form_src)
873                 default_val = m_form_src->resolveText(default_val);
874
875
876         default_val = unescape_string(default_val);
877         label = unescape_string(label);
878
879         std::wstring wlabel = narrow_to_wide(label.c_str());
880
881         FieldSpec spec = FieldSpec(
882                 narrow_to_wide(name.c_str()),
883                 wlabel,
884                 narrow_to_wide(default_val.c_str()),
885                 258+m_fields.size()
886         );
887
888         if (name == "")
889         {
890                 // spec field id to 0, this stops submit searching for a value that isn't there
891                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
892         }
893         else
894         {
895                 spec.send = true;
896                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
897                 Environment->setFocus(e);
898
899                 if (type == "textarea")
900                 {
901                         e->setMultiLine(true);
902                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
903                 } else {
904                         irr::SEvent evt;
905                         evt.EventType            = EET_KEY_INPUT_EVENT;
906                         evt.KeyInput.Key         = KEY_END;
907                         evt.KeyInput.Char        = 0;
908                         evt.KeyInput.Control     = 0;
909                         evt.KeyInput.Shift       = 0;
910                         evt.KeyInput.PressedDown = true;
911                         e->OnEvent(evt);
912                 }
913
914                 if (label.length() > 1)
915                 {
916                         rect.UpperLeftCorner.Y -= 15;
917                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
918                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
919                 }
920         }
921         m_fields.push_back(spec);
922 }
923
924 void GUIFormSpecMenu::parseField(parserData* data,std::string element,std::string type) {
925         std::vector<std::string> parts = split(element,';');
926
927         if (parts.size() == 3) {
928                 parseSimpleField(data,parts);
929                 return;
930         }
931
932         if (parts.size() == 5) {
933                 parseTextArea(data,parts,type);
934                 return;
935         }
936         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
937 }
938
939 void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) {
940         std::vector<std::string> parts = split(element,';');
941
942         if (parts.size() == 2) {
943                 std::vector<std::string> v_pos = split(parts[0],',');
944                 std::string text = parts[1];
945
946                 MY_CHECKPOS("label",0);
947
948                 v2s32 pos = padding;
949                 pos.X += stof(v_pos[0]) * (float)spacing.X;
950                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
951
952                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
953
954                 if(data->bp_set != 2)
955                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
956
957                 text = unescape_string(text);
958
959                 std::wstring wlabel = narrow_to_wide(text.c_str());
960
961                 FieldSpec spec = FieldSpec(
962                         L"",
963                         wlabel,
964                         L"",
965                         258+m_fields.size()
966                 );
967                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
968                 m_fields.push_back(spec);
969                 return;
970         }
971         errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'"  << std::endl;
972 }
973
974 void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) {
975         std::vector<std::string> parts = split(element,';');
976
977         if (parts.size() == 2) {
978                 std::vector<std::string> v_pos = split(parts[0],',');
979                 std::string text = parts[1];
980
981                 MY_CHECKPOS("vertlabel",1);
982
983                 v2s32 pos = padding;
984                 pos.X += stof(v_pos[0]) * (float)spacing.X;
985                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
986
987                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+15, pos.Y+300);
988
989                 if(data->bp_set != 2)
990                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
991
992                 text = unescape_string(text);
993                 std::string label = "";
994
995                 for (unsigned int i=0; i < text.length(); i++) {
996                         label += text.c_str()[i];
997                         label += "\n";
998                 }
999
1000                 FieldSpec spec = FieldSpec(
1001                         L"",
1002                         narrow_to_wide(label.c_str()),
1003                         L"",
1004                         258+m_fields.size()
1005                 );
1006                 gui::IGUIStaticText *t =
1007                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1008                 t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1009                 m_fields.push_back(spec);
1010                 return;
1011         }
1012         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1013 }
1014
1015 void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element,std::string type) {
1016         std::vector<std::string> parts = split(element,';');
1017
1018         if ((parts.size() == 5) || (parts.size() == 7) || (parts.size() == 8)) {
1019                 std::vector<std::string> v_pos = split(parts[0],',');
1020                 std::vector<std::string> v_geom = split(parts[1],',');
1021                 std::string image_name = parts[2];
1022                 std::string name = parts[3];
1023                 std::string label = parts[4];
1024
1025                 MY_CHECKPOS("imagebutton",0);
1026                 MY_CHECKGEOM("imagebutton",1);
1027
1028                 v2s32 pos = padding;
1029                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1030                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1031                 v2s32 geom;
1032                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1033                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1034
1035                 bool noclip = false;
1036                 bool drawborder = true;
1037
1038                 if ((parts.size() >= 7)) {
1039                         if (parts[5] == "true")
1040                                 noclip = true;
1041
1042                         if (parts[6] == "false")
1043                                 drawborder = false;
1044                 }
1045                 
1046                 std::string pressed_image_name = "";
1047                 
1048                 if ((parts.size() == 8)) {
1049                         pressed_image_name = parts[7];
1050                 }
1051
1052                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1053
1054                 if(data->bp_set != 2)
1055                         errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl;
1056
1057                 label = unescape_string(label);
1058
1059                 std::wstring wlabel = narrow_to_wide(label.c_str());
1060
1061                 FieldSpec spec = FieldSpec(
1062                         narrow_to_wide(name.c_str()),
1063                         wlabel,
1064                         narrow_to_wide(image_name.c_str()),
1065                         258+m_fields.size()
1066                 );
1067                 spec.ftype = f_Button;
1068                 if(type == "image_button_exit")
1069                         spec.is_exit = true;
1070
1071                 video::ITexture *texture = 0;
1072                 video::ITexture *pressed_texture = 0;
1073                 //if there's no gamedef specified try to get direct
1074                 //TODO check for possible texture leak
1075                 if (m_gamedef != 0) {
1076                         texture = m_gamedef->tsrc()->getTexture(image_name);
1077                         if ((parts.size() == 8)) {
1078                                 pressed_texture = m_gamedef->tsrc()->getTexture(pressed_image_name);
1079                         }
1080                 } else {
1081                         if (fs::PathExists(image_name)) {
1082                                 texture = Environment->getVideoDriver()->getTexture(image_name.c_str());
1083                                 m_Textures.push_back(texture);
1084                         }
1085                         if (fs::PathExists(pressed_image_name)) {
1086                                 pressed_texture = Environment->getVideoDriver()->getTexture(pressed_image_name.c_str());
1087                                 m_Textures.push_back(pressed_texture);
1088                         }
1089                 }
1090                 if (parts.size() < 8)
1091                         pressed_texture = texture;
1092
1093                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1094                 e->setUseAlphaChannel(true);
1095                 e->setImage(texture);
1096                 e->setPressedImage(pressed_texture);
1097                 e->setScaleImage(true);
1098                 e->setNotClipped(noclip);
1099                 e->setDrawBorder(drawborder);
1100
1101                 m_fields.push_back(spec);
1102                 return;
1103         }
1104
1105         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1106 }
1107
1108 void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element) {
1109         std::vector<std::string> parts = split(element,';');
1110
1111         if ((parts.size() == 4) || (parts.size() == 6)) {
1112                 std::vector<std::string> v_pos = split(parts[0],',');
1113                 std::string name = parts[1];
1114                 std::vector<std::string> buttons = split(parts[2],',');
1115                 std::string str_index = parts[3];
1116                 bool show_background = true;
1117                 bool show_border = true;
1118                 int tab_index = stoi(str_index) -1;
1119
1120                 MY_CHECKPOS("tabheader",0);
1121
1122                 if (parts.size() == 6) {
1123                         if (parts[4] == "true")
1124                                 show_background = false;
1125                         if (parts[5] == "false")
1126                                 show_border = false;
1127                 }
1128
1129                 FieldSpec spec = FieldSpec(
1130                         narrow_to_wide(name.c_str()),
1131                         L"",
1132                         L"",
1133                         258+m_fields.size()
1134                 );
1135
1136                 spec.ftype = f_TabHeader;
1137
1138                 v2s32 pos = padding;
1139                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1140                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1141                 v2s32 geom;
1142                 geom.X = data->screensize.Y;
1143                 geom.Y = 30;
1144
1145                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1146
1147                 gui::IGUITabControl *e = Environment->addTabControl(rect,this,show_background,show_border,spec.fid);
1148
1149                 e->setNotClipped(true);
1150
1151                 for (unsigned int i=0; i< buttons.size(); i++) {
1152                         wchar_t* wbutton = 0;
1153
1154                         wbutton = (wchar_t*) narrow_to_wide(buttons[i].c_str()).c_str();
1155
1156                         e->addTab(wbutton,-1);
1157                 }
1158
1159                 if ((tab_index >= 0) &&
1160                                 (buttons.size() < INT_MAX) &&
1161                                 (tab_index < (int) buttons.size()))
1162                         e->setActiveTab(tab_index);
1163
1164                 m_fields.push_back(spec);
1165                 return;
1166         }
1167         errorstream<< "Invalid TabHeader element(" << parts.size() << "): '" << element << "'"  << std::endl;
1168 }
1169
1170 void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element) {
1171
1172         if (m_gamedef == 0) {
1173                 errorstream<<"WARNING: invalid use of item_image_button with m_gamedef==0"<<std::endl;
1174                 return;
1175         }
1176
1177         std::vector<std::string> parts = split(element,';');
1178
1179         if (parts.size() == 5) {
1180                 std::vector<std::string> v_pos = split(parts[0],',');
1181                 std::vector<std::string> v_geom = split(parts[1],',');
1182                 std::string item_name = parts[2];
1183                 std::string name = parts[3];
1184                 std::string label = parts[4];
1185
1186                 MY_CHECKPOS("itemimagebutton",0);
1187                 MY_CHECKGEOM("itemimagebutton",1);
1188
1189                 v2s32 pos = padding;
1190                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1191                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1192                 v2s32 geom;
1193                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1194                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1195
1196                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1197
1198                 if(data->bp_set != 2)
1199                         errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl;
1200
1201                 IItemDefManager *idef = m_gamedef->idef();
1202                 ItemStack item;
1203                 item.deSerialize(item_name, idef);
1204                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
1205                 std::string tooltip = item.getDefinition(idef).description;
1206
1207                 label = unescape_string(label);
1208                 FieldSpec spec = FieldSpec(
1209                         narrow_to_wide(name.c_str()),
1210                         narrow_to_wide(label.c_str()),
1211                         narrow_to_wide(item_name.c_str()),
1212                         258+m_fields.size()
1213                 );
1214
1215                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1216                 e->setUseAlphaChannel(true);
1217                 e->setImage(texture);
1218                 e->setPressedImage(texture);
1219                 e->setScaleImage(true);
1220                 spec.ftype = f_Button;
1221                 rect+=data->basepos-padding;
1222                 spec.rect=rect;
1223                 if (tooltip!="")
1224                         spec.tooltip=tooltip;
1225                 m_fields.push_back(spec);
1226                 return;
1227         }
1228         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1229 }
1230
1231 void GUIFormSpecMenu::parseBox(parserData* data,std::string element) {
1232         std::vector<std::string> parts = split(element,';');
1233
1234         if (parts.size() == 3) {
1235                 std::vector<std::string> v_pos = split(parts[0],',');
1236                 std::vector<std::string> v_geom = split(parts[1],',');
1237                 std::string color_str = parts[2];
1238
1239                 MY_CHECKPOS("box",0);
1240                 MY_CHECKGEOM("box",1);
1241
1242                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
1243                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1244                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1245
1246                 v2s32 geom;
1247                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1248                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1249
1250                 irr::video::SColor color;
1251
1252                 if (parseColor(color_str, color)) {
1253                         BoxDrawSpec spec(pos,geom,color);
1254
1255                         m_boxes.push_back(spec);
1256                 }
1257                 else {
1258                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1259                 }
1260                 return;
1261         }
1262         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1263 }
1264
1265 void GUIFormSpecMenu::parseElement(parserData* data,std::string element) {
1266
1267         //some prechecks
1268         if (element == "")
1269                 return;
1270
1271         std::vector<std::string> parts = split(element,'[');
1272
1273         // ugly workaround to keep compatibility
1274         if (parts.size() > 2) {
1275                 if (trim(parts[0]) == "image") {
1276                         for (unsigned int i=2;i< parts.size(); i++) {
1277                                 parts[1] += "[" + parts[i];
1278                         }
1279                 }
1280                 else { return; }
1281         }
1282
1283         if (parts.size() < 2) {
1284                 return;
1285         }
1286
1287         std::string type = trim(parts[0]);
1288         std::string description = trim(parts[1]);
1289
1290         if ((type == "size") || (type == "invsize")){
1291                 parseSize(data,description);
1292                 return;
1293         }
1294
1295         if (type == "list") {
1296                 parseList(data,description);
1297                 return;
1298         }
1299
1300         if (type == "checkbox") {
1301                 parseCheckbox(data,description);
1302                 return;
1303         }
1304
1305         if (type == "image") {
1306                 parseImage(data,description);
1307                 return;
1308         }
1309
1310         if (type == "item_image") {
1311                 parseItemImage(data,description);
1312                 return;
1313         }
1314
1315         if ((type == "button") || (type == "button_exit")) {
1316                 parseButton(data,description,type);
1317                 return;
1318         }
1319
1320         if (type == "background") {
1321                 parseBackground(data,description);
1322                 return;
1323         }
1324
1325         if (type == "textlist"){
1326                 parseTextList(data,description);
1327                 return;
1328         }
1329
1330         if (type == "dropdown"){
1331                 parseDropDown(data,description);
1332                 return;
1333         }
1334
1335         if (type == "pwdfield") {
1336                 parsePwdField(data,description);
1337                 return;
1338         }
1339
1340         if ((type == "field") || (type == "textarea")){
1341                 parseField(data,description,type);
1342                 return;
1343         }
1344
1345         if (type == "label") {
1346                 parseLabel(data,description);
1347                 return;
1348         }
1349
1350         if (type == "vertlabel") {
1351                 parseVertLabel(data,description);
1352                 return;
1353         }
1354
1355         if (type == "item_image_button") {
1356                 parseItemImageButton(data,description);
1357                 return;
1358         }
1359
1360         if ((type == "image_button") || (type == "image_button_exit")) {
1361                 parseImageButton(data,description,type);
1362                 return;
1363         }
1364
1365         if (type == "tabheader") {
1366                 parseTabHeader(data,description);
1367                 return;
1368         }
1369
1370         if (type == "box") {
1371                 parseBox(data,description);
1372                 return;
1373         }
1374
1375         // Ignore others
1376         infostream
1377                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1378                 <<std::endl;
1379 }
1380
1381
1382
1383 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1384 {
1385         parserData mydata;
1386
1387         //preserve listboxes
1388         for (unsigned int i = 0; i < m_listboxes.size(); i++) {
1389                 std::wstring listboxname = m_listboxes[i].first.fname;
1390                 gui::IGUIListBox *listbox = m_listboxes[i].second;
1391
1392                 int selection = listbox->getSelected();
1393                 if (selection != -1) {
1394                         mydata.listbox_selections[listboxname] = selection;
1395                 }
1396
1397                 gui::IGUIScrollBar *scrollbar = getListboxScrollbar(listbox);
1398                 if (scrollbar) {
1399                         mydata.listbox_scroll[listboxname] = scrollbar->getPos();
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,']');
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()
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
1978                                         if (m_listbox_doubleclick) {
1979                                                 ss << "DCL:";
1980                                         }
1981                                         else {
1982                                                 ss << "CHG:";
1983                                         }
1984                                         ss << (getListboxIndex(wide_to_narrow(s.fname.c_str()))+1);
1985                                         fields[wide_to_narrow(s.fname.c_str())] = ss.str();
1986                                 }
1987                                 else if(s.ftype == f_DropDown) {
1988                                         // no dynamic cast possible due to some distributions shipped
1989                                         // without rtti support in irrlicht
1990                                         IGUIElement * element = getElementFromId(s.fid);
1991                                         gui::IGUIComboBox *e = NULL;
1992                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
1993                                                 e = static_cast<gui::IGUIComboBox*>(element);
1994                                         }
1995                                         fields[wide_to_narrow(s.fname.c_str())] =
1996                                                         wide_to_narrow(e->getItem(e->getSelected()));
1997                                 }
1998                                 else if (s.ftype == f_TabHeader) {
1999                                         // no dynamic cast possible due to some distributions shipped
2000                                         // without rtti support in irrlicht
2001                                         IGUIElement * element = getElementFromId(s.fid);
2002                                         gui::IGUITabControl *e = NULL;
2003                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2004                                                 e = static_cast<gui::IGUITabControl*>(element);
2005                                         }
2006
2007                                         if (e != 0) {
2008                                                 std::stringstream ss;
2009                                                 ss << (e->getActiveTab() +1);
2010                                                 fields[wide_to_narrow(s.fname.c_str())] = ss.str();
2011                                         }
2012                                 }
2013                                 else if (s.ftype == f_CheckBox) {
2014                                         // no dynamic cast possible due to some distributions shipped
2015                                         // without rtti support in irrlicht
2016                                         IGUIElement * element = getElementFromId(s.fid);
2017                                         gui::IGUICheckBox *e = NULL;
2018                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2019                                                 e = static_cast<gui::IGUICheckBox*>(element);
2020                                         }
2021
2022                                         if (e != 0) {
2023                                                 if (e->isChecked())
2024                                                         fields[wide_to_narrow(s.fname.c_str())] = "true";
2025                                                 else
2026                                                         fields[wide_to_narrow(s.fname.c_str())] = "false";
2027                                         }
2028                                 }
2029                                 else
2030                                 {
2031                                         IGUIElement* e = getElementFromId(s.fid);
2032                                         if(e != NULL)
2033                                         {
2034                                                 fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(e->getText());
2035                                         }
2036                                 }
2037                         }
2038                 }
2039
2040                 m_text_dst->gotText(fields);
2041         }
2042 }
2043
2044 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
2045 {
2046         if(event.EventType==EET_KEY_INPUT_EVENT)
2047         {
2048                 KeyPress kp(event.KeyInput);
2049                 if (event.KeyInput.PressedDown && (kp == EscapeKey ||
2050                         kp == getKeySetting("keymap_inventory")))
2051                 {
2052                         if (m_allowclose)
2053                                 quitMenu();
2054                         else
2055                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
2056                         return true;
2057                 }
2058                 if (event.KeyInput.PressedDown &&
2059                         (event.KeyInput.Key==KEY_RETURN ||
2060                          event.KeyInput.Key==KEY_UP ||
2061                          event.KeyInput.Key==KEY_DOWN)
2062                         ) {
2063
2064
2065                         switch (event.KeyInput.Key) {
2066                                 case KEY_RETURN:
2067                                         if (m_allowclose) {
2068                                                 acceptInput();
2069                                                 quitMenu();
2070                                         }
2071                                         else
2072                                                 current_keys_pending.key_enter = true;
2073                                         break;
2074                                 case KEY_UP:
2075                                         current_keys_pending.key_up = true;
2076                                         break;
2077                                 case KEY_DOWN:
2078                                         current_keys_pending.key_down = true;
2079                                         break;
2080                                 break;
2081                                 default:
2082                                         //can't happen at all!
2083                                         assert("reached a source line that can't ever been reached" == 0);
2084                                         break;
2085                         }
2086                         acceptInput();
2087                         return true;
2088                 }
2089
2090         }
2091         if(event.EventType==EET_MOUSE_INPUT_EVENT
2092                         && event.MouseInput.Event != EMIE_MOUSE_MOVED)
2093         {
2094                 // Mouse event other than movement
2095
2096                 // Get selected item and hovered/clicked item (s)
2097
2098                 updateSelectedItem();
2099                 ItemSpec s = getItemAtPos(m_pointer);
2100
2101                 Inventory *inv_selected = NULL;
2102                 Inventory *inv_s = NULL;
2103
2104                 if(m_selected_item)
2105                 {
2106                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
2107                         assert(inv_selected);
2108                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
2109                 }
2110
2111                 u32 s_count = 0;
2112
2113                 if(s.isValid())
2114                 do{ // breakable
2115                         inv_s = m_invmgr->getInventory(s.inventoryloc);
2116
2117                         if(!inv_s){
2118                                 errorstream<<"InventoryMenu: The selected inventory location "
2119                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2120                                                 <<std::endl;
2121                                 s.i = -1;  // make it invalid again
2122                                 break;
2123                         }
2124
2125                         InventoryList *list = inv_s->getList(s.listname);
2126                         if(list == NULL){
2127                                 verbosestream<<"InventoryMenu: The selected inventory list \""
2128                                                 <<s.listname<<"\" does not exist"<<std::endl;
2129                                 s.i = -1;  // make it invalid again
2130                                 break;
2131                         }
2132
2133                         if((u32)s.i >= list->getSize()){
2134                                 infostream<<"InventoryMenu: The selected inventory list \""
2135                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
2136                                                 <<list->getSize()<<")"<<std::endl;
2137                                 s.i = -1;  // make it invalid again
2138                                 break;
2139                         }
2140
2141                         s_count = list->getItem(s.i).count;
2142                 }while(0);
2143
2144                 bool identical = (m_selected_item != NULL) && s.isValid() &&
2145                         (inv_selected == inv_s) &&
2146                         (m_selected_item->listname == s.listname) &&
2147                         (m_selected_item->i == s.i);
2148
2149                 // buttons: 0 = left, 1 = right, 2 = middle
2150                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event
2151                 int button = 0;
2152                 int updown = 2;
2153                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
2154                         { button = 0; updown = 0; }
2155                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
2156                         { button = 1; updown = 0; }
2157                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
2158                         { button = 2; updown = 0; }
2159                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
2160                         { button = 0; updown = 1; }
2161                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
2162                         { button = 1; updown = 1; }
2163                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
2164                         { button = 2; updown = 1; }
2165
2166                 // Set this number to a positive value to generate a move action
2167                 // from m_selected_item to s.
2168                 u32 move_amount = 0;
2169
2170                 // Set this number to a positive value to generate a drop action
2171                 // from m_selected_item.
2172                 u32 drop_amount = 0;
2173
2174                 // Set this number to a positive value to generate a craft action at s.
2175                 u32 craft_amount = 0;
2176
2177                 if(updown == 0)
2178                 {
2179                         // Some mouse button has been pressed
2180
2181                         //infostream<<"Mouse button "<<button<<" pressed at p=("
2182                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2183
2184                         m_selected_dragging = false;
2185
2186                         if(s.isValid() && s.listname == "craftpreview")
2187                         {
2188                                 // Craft preview has been clicked: craft
2189                                 craft_amount = (button == 2 ? 10 : 1);
2190                         }
2191                         else if(m_selected_item == NULL)
2192                         {
2193                                 if(s_count != 0)
2194                                 {
2195                                         // Non-empty stack has been clicked: select it
2196                                         m_selected_item = new ItemSpec(s);
2197
2198                                         if(button == 1)  // right
2199                                                 m_selected_amount = (s_count + 1) / 2;
2200                                         else if(button == 2)  // middle
2201                                                 m_selected_amount = MYMIN(s_count, 10);
2202                                         else  // left
2203                                                 m_selected_amount = s_count;
2204
2205                                         m_selected_dragging = true;
2206                                 }
2207                         }
2208                         else  // m_selected_item != NULL
2209                         {
2210                                 assert(m_selected_amount >= 1);
2211
2212                                 if(s.isValid())
2213                                 {
2214                                         // Clicked a slot: move
2215                                         if(button == 1)  // right
2216                                                 move_amount = 1;
2217                                         else if(button == 2)  // middle
2218                                                 move_amount = MYMIN(m_selected_amount, 10);
2219                                         else  // left
2220                                                 move_amount = m_selected_amount;
2221
2222                                         if(identical)
2223                                         {
2224                                                 if(move_amount >= m_selected_amount)
2225                                                         m_selected_amount = 0;
2226                                                 else
2227                                                         m_selected_amount -= move_amount;
2228                                                 move_amount = 0;
2229                                         }
2230                                 }
2231                                 else if(getAbsoluteClippingRect().isPointInside(m_pointer))
2232                                 {
2233                                         // Clicked somewhere else: deselect
2234                                         m_selected_amount = 0;
2235                                 }
2236                                 else
2237                                 {
2238                                         // Clicked outside of the window: drop
2239                                         if(button == 1)  // right
2240                                                 drop_amount = 1;
2241                                         else if(button == 2)  // middle
2242                                                 drop_amount = MYMIN(m_selected_amount, 10);
2243                                         else  // left
2244                                                 drop_amount = m_selected_amount;
2245                                 }
2246                         }
2247                 }
2248                 else if(updown == 1)
2249                 {
2250                         // Some mouse button has been released
2251
2252                         //infostream<<"Mouse button "<<button<<" released at p=("
2253                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2254
2255                         if(m_selected_item != NULL && m_selected_dragging && s.isValid())
2256                         {
2257                                 if(!identical)
2258                                 {
2259                                         // Dragged to different slot: move all selected
2260                                         move_amount = m_selected_amount;
2261                                 }
2262                         }
2263                         else if(m_selected_item != NULL && m_selected_dragging &&
2264                                 !(getAbsoluteClippingRect().isPointInside(m_pointer)))
2265                         {
2266                                 // Dragged outside of window: drop all selected
2267                                 drop_amount = m_selected_amount;
2268                         }
2269
2270                         m_selected_dragging = false;
2271                 }
2272
2273                 // Possibly send inventory action to server
2274                 if(move_amount > 0)
2275                 {
2276                         // Send IACTION_MOVE
2277
2278                         assert(m_selected_item && m_selected_item->isValid());
2279                         assert(s.isValid());
2280
2281                         assert(inv_selected && inv_s);
2282                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2283                         InventoryList *list_to = inv_s->getList(s.listname);
2284                         assert(list_from && list_to);
2285                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2286                         ItemStack stack_to = list_to->getItem(s.i);
2287
2288                         // Check how many items can be moved
2289                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
2290                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
2291                         // If source stack cannot be added to destination stack at all,
2292                         // they are swapped
2293                         if(leftover.count == stack_from.count && leftover.name == stack_from.name)
2294                         {
2295                                 m_selected_amount = stack_to.count;
2296                                 // In case the server doesn't directly swap them but instead
2297                                 // moves stack_to somewhere else, set this
2298                                 m_selected_content_guess = stack_to;
2299                                 m_selected_content_guess_inventory = s.inventoryloc;
2300                         }
2301                         // Source stack goes fully into destination stack
2302                         else if(leftover.empty())
2303                         {
2304                                 m_selected_amount -= move_amount;
2305                                 m_selected_content_guess = ItemStack(); // Clear
2306                         }
2307                         // Source stack goes partly into destination stack
2308                         else
2309                         {
2310                                 move_amount -= leftover.count;
2311                                 m_selected_amount -= move_amount;
2312                                 m_selected_content_guess = ItemStack(); // Clear
2313                         }
2314
2315                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
2316                         IMoveAction *a = new IMoveAction();
2317                         a->count = move_amount;
2318                         a->from_inv = m_selected_item->inventoryloc;
2319                         a->from_list = m_selected_item->listname;
2320                         a->from_i = m_selected_item->i;
2321                         a->to_inv = s.inventoryloc;
2322                         a->to_list = s.listname;
2323                         a->to_i = s.i;
2324                         m_invmgr->inventoryAction(a);
2325                 }
2326                 else if(drop_amount > 0)
2327                 {
2328                         m_selected_content_guess = ItemStack(); // Clear
2329
2330                         // Send IACTION_DROP
2331
2332                         assert(m_selected_item && m_selected_item->isValid());
2333                         assert(inv_selected);
2334                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2335                         assert(list_from);
2336                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2337
2338                         // Check how many items can be dropped
2339                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
2340                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
2341                         m_selected_amount -= drop_amount;
2342
2343                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
2344                         IDropAction *a = new IDropAction();
2345                         a->count = drop_amount;
2346                         a->from_inv = m_selected_item->inventoryloc;
2347                         a->from_list = m_selected_item->listname;
2348                         a->from_i = m_selected_item->i;
2349                         m_invmgr->inventoryAction(a);
2350                 }
2351                 else if(craft_amount > 0)
2352                 {
2353                         m_selected_content_guess = ItemStack(); // Clear
2354
2355                         // Send IACTION_CRAFT
2356
2357                         assert(s.isValid());
2358                         assert(inv_s);
2359
2360                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
2361                         ICraftAction *a = new ICraftAction();
2362                         a->count = craft_amount;
2363                         a->craft_inv = s.inventoryloc;
2364                         m_invmgr->inventoryAction(a);
2365                 }
2366
2367                 // If m_selected_amount has been decreased to zero, deselect
2368                 if(m_selected_amount == 0)
2369                 {
2370                         delete m_selected_item;
2371                         m_selected_item = NULL;
2372                         m_selected_amount = 0;
2373                         m_selected_dragging = false;
2374                         m_selected_content_guess = ItemStack();
2375                 }
2376         }
2377         if(event.EventType==EET_GUI_EVENT)
2378         {
2379
2380                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
2381                                                 && isVisible())
2382                 {
2383                         // find the element that was clicked
2384                         for(u32 i=0; i<m_fields.size(); i++)
2385                         {
2386                                 FieldSpec &s = m_fields[i];
2387                                 // if its a button, set the send field so
2388                                 // lua knows which button was pressed
2389                                 if ((s.ftype == f_TabHeader) && (s.fid == event.GUIEvent.Caller->getID()))
2390                                 {
2391                                         s.send = true;
2392                                         acceptInput();
2393                                         s.send = false;
2394                                         // Restore focus to the full form
2395                                         Environment->setFocus(this);
2396                                         return true;
2397                                 }
2398                         }
2399                 }
2400                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
2401                                 && isVisible())
2402                 {
2403                         if(!canTakeFocus(event.GUIEvent.Element))
2404                         {
2405                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
2406                                                 <<std::endl;
2407                                 // Returning true disables focus change
2408                                 return true;
2409                         }
2410                 }
2411                 if((event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED) ||
2412                                 (event.GUIEvent.EventType==gui::EGET_CHECKBOX_CHANGED))
2413                 {
2414                         unsigned int btn_id = event.GUIEvent.Caller->getID();
2415
2416                         if (btn_id == 257) {
2417                                 acceptInput();
2418                                 if (m_allowclose)
2419                                         quitMenu();
2420                                 else
2421                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2422                                 // quitMenu deallocates menu
2423                                 return true;
2424                         }
2425
2426                         // find the element that was clicked
2427                         for(u32 i=0; i<m_fields.size(); i++)
2428                         {
2429                                 FieldSpec &s = m_fields[i];
2430                                 // if its a button, set the send field so 
2431                                 // lua knows which button was pressed
2432                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
2433                                                 (s.fid == event.GUIEvent.Caller->getID()))
2434                                 {
2435                                         s.send = true;
2436                                         acceptInput();
2437                                         if(s.is_exit){
2438                                                 if (m_allowclose)
2439                                                         quitMenu();
2440                                                 else
2441                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2442                                                 return true;
2443                                         }else{
2444                                                 s.send = false;
2445                                                 // Restore focus to the full form
2446                                                 Environment->setFocus(this);
2447                                                 return true;
2448                                         }
2449                                 }
2450                         }
2451                 }
2452                 if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER)
2453                 {
2454                         if(event.GUIEvent.Caller->getID() > 257)
2455                         {
2456
2457                                 if (m_allowclose) {
2458                                         acceptInput();
2459                                         quitMenu();
2460                                 }
2461                                 else {
2462                                         current_keys_pending.key_enter = true;
2463                                         acceptInput();
2464                                 }
2465                                 // quitMenu deallocates menu
2466                                 return true;
2467                         }
2468                 }
2469
2470                 if((event.GUIEvent.EventType==gui::EGET_LISTBOX_SELECTED_AGAIN) ||
2471                         (event.GUIEvent.EventType==gui::EGET_LISTBOX_CHANGED))
2472                 {
2473                         int current_id = event.GUIEvent.Caller->getID();
2474                         if(current_id > 257)
2475                         {
2476                                 // find the element that was clicked
2477                                 for(u32 i=0; i<m_fields.size(); i++)
2478                                 {
2479                                         FieldSpec &s = m_fields[i];
2480                                         // if its a listbox, set the send field so
2481                                         // lua knows which listbox was changed
2482                                         // checkListboxClick() is black magic
2483                                         // for properly handling double clicks
2484                                         if ((s.ftype == f_ListBox) && (s.fid == current_id)
2485                                                         && checkListboxClick(s.fname,
2486                                                                 event.GUIEvent.EventType))
2487                                         {
2488                                                 s.send = true;
2489                                                 acceptInput();
2490                                                 s.send=false;
2491                                                 // Restore focus to the full form
2492                                                 Environment->setFocus(this);
2493                                         }
2494                                 }
2495                                 return true;
2496                         }
2497                 }
2498         }
2499
2500         return Parent ? Parent->OnEvent(event) : false;
2501 }
2502
2503 bool GUIFormSpecMenu::parseColor(std::string color, irr::video::SColor& outcolor) {
2504         outcolor = irr::video::SColor(0,0,0,0);
2505
2506         if (!string_allowed(color, "0123456789abcdefABCDEF"))
2507                 return false;
2508
2509         u32 color_value;
2510         std::istringstream iss(color);
2511         iss >> std::hex >> color_value;
2512         
2513         outcolor = irr::video::SColor(color_value);
2514
2515         outcolor.setAlpha(255);
2516         return true;
2517 }