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