]> git.lizzy.rs Git - minetest.git/blob - src/guiFormSpecMenu.cpp
Fix memory leaks due to messed up memory handling for particles as well as their...
[minetest.git] / src / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <sstream>
25 #include <limits>
26 #include "guiFormSpecMenu.h"
27 #include "guiTable.h"
28 #include "constants.h"
29 #include "gamedef.h"
30 #include "keycode.h"
31 #include "strfnd.h"
32 #include <IGUICheckBox.h>
33 #include <IGUIEditBox.h>
34 #include <IGUIButton.h>
35 #include <IGUIStaticText.h>
36 #include <IGUIFont.h>
37 #include <IGUITabControl.h>
38 #include <IGUIComboBox.h>
39 #include "log.h"
40 #include "tile.h" // ITextureSource
41 #include "hud.h" // drawItemStack
42 #include "hex.h"
43 #include "util/string.h"
44 #include "util/numeric.h"
45 #include "filesys.h"
46 #include "gettime.h"
47 #include "gettext.h"
48 #include "scripting_game.h"
49 #include "porting.h"
50 #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.5555 * 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                 target_font_height *= g_settings->getFloat("font_size")/TTF_DEFAULT_FONT_SIZE;
1979                 m_btn_height = use_imgsize*15.0/13 * 0.35;
1980
1981                 m_font = select_font_by_line_height(target_font_height);
1982
1983                 mydata.size = v2s32(
1984                         padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
1985                         padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
1986                 );
1987                 DesiredRect = mydata.rect = core::rect<s32>(
1988                                 mydata.screensize.X/2 - mydata.size.X/2 + offset.X,
1989                                 mydata.screensize.Y/2 - mydata.size.Y/2 + offset.Y,
1990                                 mydata.screensize.X/2 + mydata.size.X/2 + offset.X,
1991                                 mydata.screensize.Y/2 + mydata.size.Y/2 + offset.Y
1992                 );
1993         } else {
1994                 // Non-size[] form must consist only of text fields and
1995                 // implicit "Proceed" button.  Use default font, and
1996                 // temporary form size which will be recalculated below.
1997                 m_font = g_fontengine->getFont();
1998                 m_btn_height = font_line_height(m_font) * 0.875;
1999                 DesiredRect = core::rect<s32>(
2000                         mydata.screensize.X/2 - 580/2,
2001                         mydata.screensize.Y/2 - 300/2,
2002                         mydata.screensize.X/2 + 580/2,
2003                         mydata.screensize.Y/2 + 300/2
2004                 );
2005         }
2006         recalculateAbsolutePosition(false);
2007         mydata.basepos = getBasePos();
2008         m_tooltip_element->setOverrideFont(m_font);
2009
2010         gui::IGUISkin* skin = Environment->getSkin();
2011         assert(skin != NULL);
2012         gui::IGUIFont *old_font = skin->getFont();
2013         skin->setFont(m_font);
2014
2015         for (; i< elements.size(); i++) {
2016                 parseElement(&mydata, elements[i]);
2017         }
2018
2019         // If there are fields without explicit size[], add a "Proceed"
2020         // button and adjust size to fit all the fields.
2021         if (m_fields.size() && !mydata.explicit_size) {
2022                 mydata.rect = core::rect<s32>(
2023                                 mydata.screensize.X/2 - 580/2,
2024                                 mydata.screensize.Y/2 - 300/2,
2025                                 mydata.screensize.X/2 + 580/2,
2026                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
2027                 );
2028                 DesiredRect = mydata.rect;
2029                 recalculateAbsolutePosition(false);
2030                 mydata.basepos = getBasePos();
2031
2032                 {
2033                         v2s32 pos = mydata.basepos;
2034                         pos.Y = ((m_fields.size()+2)*60);
2035
2036                         v2s32 size = DesiredRect.getSize();
2037                         mydata.rect =
2038                                         core::rect<s32>(size.X/2-70, pos.Y,
2039                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2040                         wchar_t* text = wgettext("Proceed");
2041                         Environment->addButton(mydata.rect, this, 257, text);
2042                         delete[] text;
2043                 }
2044
2045         }
2046
2047         //set initial focus if parser didn't set it
2048         focused_element = Environment->getFocus();
2049         if (!focused_element
2050                         || !isMyChild(focused_element)
2051                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2052                 setInitialFocus();
2053
2054         skin->setFont(old_font);
2055 }
2056
2057 #ifdef __ANDROID__
2058 bool GUIFormSpecMenu::getAndroidUIInput()
2059 {
2060         /* no dialog shown */
2061         if (m_JavaDialogFieldName == L"") {
2062                 return false;
2063         }
2064
2065         /* still waiting */
2066         if (porting::getInputDialogState() == -1) {
2067                 return true;
2068         }
2069
2070         std::wstring fieldname = m_JavaDialogFieldName;
2071         m_JavaDialogFieldName = L"";
2072
2073         /* no value abort dialog processing */
2074         if (porting::getInputDialogState() != 0) {
2075                 return false;
2076         }
2077
2078         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2079                         iter != m_fields.end(); iter++) {
2080
2081                 if (iter->fname != fieldname) {
2082                         continue;
2083                 }
2084                 IGUIElement* tochange = getElementFromId(iter->fid);
2085
2086                 if (tochange == 0) {
2087                         return false;
2088                 }
2089
2090                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2091                         return false;
2092                 }
2093
2094                 std::string text = porting::getInputDialogValue();
2095
2096                 ((gui::IGUIEditBox*) tochange)->
2097                         setText(narrow_to_wide(text).c_str());
2098         }
2099         return false;
2100 }
2101 #endif
2102
2103 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2104 {
2105         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2106
2107         for(u32 i=0; i<m_inventorylists.size(); i++)
2108         {
2109                 const ListDrawSpec &s = m_inventorylists[i];
2110
2111                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2112                         s32 item_i = i + s.start_item_i;
2113                         s32 x = (i%s.geom.X) * spacing.X;
2114                         s32 y = (i/s.geom.X) * spacing.Y;
2115                         v2s32 p0(x,y);
2116                         core::rect<s32> rect = imgrect + s.pos + p0;
2117                         if(rect.isPointInside(p))
2118                         {
2119                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2120                         }
2121                 }
2122         }
2123
2124         return ItemSpec(InventoryLocation(), "", -1);
2125 }
2126
2127 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
2128 {
2129         video::IVideoDriver* driver = Environment->getVideoDriver();
2130
2131         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2132         if(!inv){
2133                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2134                                 <<"The inventory location "
2135                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2136                                 <<std::endl;
2137                 return;
2138         }
2139         InventoryList *ilist = inv->getList(s.listname);
2140         if(!ilist){
2141                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
2142                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2143                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2144                                 <<std::endl;
2145                 return;
2146         }
2147
2148         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2149
2150         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
2151         {
2152                 s32 item_i = i + s.start_item_i;
2153                 if(item_i >= (s32) ilist->getSize())
2154                         break;
2155                 s32 x = (i%s.geom.X) * spacing.X;
2156                 s32 y = (i/s.geom.X) * spacing.Y;
2157                 v2s32 p(x,y);
2158                 core::rect<s32> rect = imgrect + s.pos + p;
2159                 ItemStack item;
2160                 if(ilist)
2161                         item = ilist->getItem(item_i);
2162
2163                 bool selected = m_selected_item
2164                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2165                         && m_selected_item->listname == s.listname
2166                         && m_selected_item->i == item_i;
2167                 bool hovering = rect.isPointInside(m_pointer);
2168
2169                 if(phase == 0)
2170                 {
2171                         if(hovering)
2172                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2173                         else
2174                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2175                 }
2176
2177                 //Draw inv slot borders
2178                 if (m_slotborder) {
2179                         s32 x1 = rect.UpperLeftCorner.X;
2180                         s32 y1 = rect.UpperLeftCorner.Y;
2181                         s32 x2 = rect.LowerRightCorner.X;
2182                         s32 y2 = rect.LowerRightCorner.Y;
2183                         s32 border = 1;
2184                         driver->draw2DRectangle(m_slotbordercolor,
2185                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2186                                                                 v2s32(x2 + border, y1)), NULL);
2187                         driver->draw2DRectangle(m_slotbordercolor,
2188                                 core::rect<s32>(v2s32(x1 - border, y2),
2189                                                                 v2s32(x2 + border, y2 + border)), NULL);
2190                         driver->draw2DRectangle(m_slotbordercolor,
2191                                 core::rect<s32>(v2s32(x1 - border, y1),
2192                                                                 v2s32(x1, y2)), NULL);
2193                         driver->draw2DRectangle(m_slotbordercolor,
2194                                 core::rect<s32>(v2s32(x2, y1),
2195                                                                 v2s32(x2 + border, y2)), NULL);
2196                 }
2197
2198                 if(phase == 1)
2199                 {
2200                         // Draw item stack
2201                         if(selected)
2202                         {
2203                                 item.takeItem(m_selected_amount);
2204                         }
2205                         if(!item.empty())
2206                         {
2207                                 drawItemStack(driver, m_font, item,
2208                                                 rect, &AbsoluteClippingRect, m_gamedef);
2209                         }
2210
2211                         // Draw tooltip
2212                         std::string tooltip_text = "";
2213                         if (hovering && !m_selected_item)
2214                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
2215                         if (tooltip_text != "") {
2216                                 std::vector<std::string> tt_rows = str_split(tooltip_text, '\n');
2217                                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2218                                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2219                                 m_tooltip_element->setVisible(true);
2220                                 this->bringToFront(m_tooltip_element);
2221                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
2222                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2223                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2224                                 v2u32 screenSize = driver->getScreenSize();
2225                                 int tooltip_offset_x = m_btn_height;
2226                                 int tooltip_offset_y = m_btn_height;
2227 #ifdef __ANDROID__
2228                                 tooltip_offset_x *= 3;
2229                                 tooltip_offset_y  = 0;
2230                                 if (m_pointer.X > (s32)screenSize.X / 2)
2231                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2232 #endif
2233                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2234                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2235                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2236                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2237                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2238                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2239                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2240                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2241                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2242                         }
2243                 }
2244         }
2245 }
2246
2247 void GUIFormSpecMenu::drawSelectedItem()
2248 {
2249         if(!m_selected_item)
2250                 return;
2251
2252         video::IVideoDriver* driver = Environment->getVideoDriver();
2253
2254         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2255         assert(inv);
2256         InventoryList *list = inv->getList(m_selected_item->listname);
2257         assert(list);
2258         ItemStack stack = list->getItem(m_selected_item->i);
2259         stack.count = m_selected_amount;
2260
2261         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2262         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2263         drawItemStack(driver, m_font, stack, rect, NULL, m_gamedef);
2264 }
2265
2266 void GUIFormSpecMenu::drawMenu()
2267 {
2268         if(m_form_src){
2269                 std::string newform = m_form_src->getForm();
2270                 if(newform != m_formspec_string){
2271                         m_formspec_string = newform;
2272                         regenerateGui(m_screensize_old);
2273                 }
2274         }
2275
2276         gui::IGUISkin* skin = Environment->getSkin();
2277         assert(skin != NULL);
2278         gui::IGUIFont *old_font = skin->getFont();
2279         skin->setFont(m_font);
2280
2281         updateSelectedItem();
2282
2283         video::IVideoDriver* driver = Environment->getVideoDriver();
2284
2285         v2u32 screenSize = driver->getScreenSize();
2286         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
2287         if (m_bgfullscreen)
2288                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
2289         else
2290                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2291
2292         m_tooltip_element->setVisible(false);
2293
2294         /*
2295                 Draw backgrounds
2296         */
2297         for(u32 i=0; i<m_backgrounds.size(); i++)
2298         {
2299                 const ImageDrawSpec &spec = m_backgrounds[i];
2300                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2301
2302                 if (texture != 0) {
2303                         // Image size on screen
2304                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2305                         // Image rectangle on screen
2306                         core::rect<s32> rect = imgrect + spec.pos;
2307
2308                         if (m_clipbackground) {
2309                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2310                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2311                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2312                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2313                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2314                         }
2315
2316                         const video::SColor color(255,255,255,255);
2317                         const video::SColor colors[] = {color,color,color,color};
2318                         driver->draw2DImage(texture, rect,
2319                                 core::rect<s32>(core::position2d<s32>(0,0),
2320                                                 core::dimension2di(texture->getOriginalSize())),
2321                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2322                 }
2323                 else {
2324                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2325                         errorstream << "\t" << spec.name << std::endl;
2326                 }
2327         }
2328
2329         /*
2330                 Draw Boxes
2331         */
2332         for(u32 i=0; i<m_boxes.size(); i++)
2333         {
2334                 const BoxDrawSpec &spec = m_boxes[i];
2335
2336                 irr::video::SColor todraw = spec.color;
2337
2338                 todraw.setAlpha(140);
2339
2340                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2341                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2342
2343                 driver->draw2DRectangle(todraw, rect, 0);
2344         }
2345         /*
2346                 Draw images
2347         */
2348         for(u32 i=0; i<m_images.size(); i++)
2349         {
2350                 const ImageDrawSpec &spec = m_images[i];
2351                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2352
2353                 if (texture != 0) {
2354                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2355                         // Image size on screen
2356                         core::rect<s32> imgrect;
2357
2358                         if (spec.scale)
2359                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2360                         else {
2361
2362                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2363                         }
2364                         // Image rectangle on screen
2365                         core::rect<s32> rect = imgrect + spec.pos;
2366                         const video::SColor color(255,255,255,255);
2367                         const video::SColor colors[] = {color,color,color,color};
2368                         driver->draw2DImage(texture, rect,
2369                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2370                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2371                 }
2372                 else {
2373                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2374                         errorstream << "\t" << spec.name << std::endl;
2375                 }
2376         }
2377
2378         /*
2379                 Draw item images
2380         */
2381         for(u32 i=0; i<m_itemimages.size(); i++)
2382         {
2383                 if (m_gamedef == 0)
2384                         break;
2385
2386                 const ImageDrawSpec &spec = m_itemimages[i];
2387                 IItemDefManager *idef = m_gamedef->idef();
2388                 ItemStack item;
2389                 item.deSerialize(spec.name, idef);
2390                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
2391                 // Image size on screen
2392                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2393                 // Image rectangle on screen
2394                 core::rect<s32> rect = imgrect + spec.pos;
2395                 const video::SColor color(255,255,255,255);
2396                 const video::SColor colors[] = {color,color,color,color};
2397                 driver->draw2DImage(texture, rect,
2398                         core::rect<s32>(core::position2d<s32>(0,0),
2399                                         core::dimension2di(texture->getOriginalSize())),
2400                         NULL/*&AbsoluteClippingRect*/, colors, true);
2401         }
2402
2403         /*
2404                 Draw items
2405                 Phase 0: Item slot rectangles
2406                 Phase 1: Item images; prepare tooltip
2407         */
2408         int start_phase=0;
2409         for(int phase=start_phase; phase<=1; phase++)
2410         for(u32 i=0; i<m_inventorylists.size(); i++)
2411         {
2412                 drawList(m_inventorylists[i], phase);
2413         }
2414
2415         /*
2416                 Call base class
2417         */
2418         gui::IGUIElement::draw();
2419
2420 /* TODO find way to show tooltips on touchscreen */
2421 #ifndef HAVE_TOUCHSCREENGUI
2422         m_pointer = m_device->getCursorControl()->getPosition();
2423 #endif
2424
2425         /*
2426                 Draw fields/buttons tooltips
2427         */
2428         gui::IGUIElement *hovered =
2429                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2430
2431         if (hovered != NULL) {
2432                 s32 id = hovered->getID();
2433
2434                 u32 delta = 0;
2435                 if (id == -1) {
2436                         m_old_tooltip_id = id;
2437                         m_old_tooltip = "";
2438                 } else {
2439                         if (id == m_old_tooltip_id) {
2440                                 delta = porting::getDeltaMs(m_hovered_time, getTimeMs());
2441                         } else {
2442                                 m_hovered_time = getTimeMs();
2443                                 m_old_tooltip_id = id;
2444                         }
2445                 }
2446
2447                 if (id != -1 && delta >= m_tooltip_show_delay) {
2448                         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2449                                         iter != m_fields.end(); iter++) {
2450                                 if ( (iter->fid == id) && (m_tooltips[iter->fname].tooltip != "") ){
2451                                         if (m_old_tooltip != m_tooltips[iter->fname].tooltip) {
2452                                                 m_old_tooltip = m_tooltips[iter->fname].tooltip;
2453                                                 m_tooltip_element->setText(narrow_to_wide(m_tooltips[iter->fname].tooltip).c_str());
2454                                                 std::vector<std::string> tt_rows = str_split(m_tooltips[iter->fname].tooltip, '\n');
2455                                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2456                                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5;
2457                                                 int tooltip_offset_x = m_btn_height;
2458                                                 int tooltip_offset_y = m_btn_height;
2459 #ifdef __ANDROID__
2460                                                 tooltip_offset_x *= 3;
2461                                                 tooltip_offset_y  = 0;
2462                                                 if (m_pointer.X > (s32)screenSize.X / 2)
2463                                                         tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1;
2464 #endif
2465                                                 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2466                                                 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2467                                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2468                                                         tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2469                                                 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2470                                                         tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2471                                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2472                                                 core::position2d<s32>(tooltip_x, tooltip_y),
2473                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2474                                         }
2475                                         m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor);
2476                                         m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color);
2477                                         m_tooltip_element->setVisible(true);
2478                                         this->bringToFront(m_tooltip_element);
2479                                         break;
2480                                 }
2481                         }
2482                 }
2483         }
2484
2485         /*
2486                 Draw dragged item stack
2487         */
2488         drawSelectedItem();
2489
2490         skin->setFont(old_font);
2491 }
2492
2493 void GUIFormSpecMenu::updateSelectedItem()
2494 {
2495         // If the selected stack has become empty for some reason, deselect it.
2496         // If the selected stack has become inaccessible, deselect it.
2497         // If the selected stack has become smaller, adjust m_selected_amount.
2498         ItemStack selected = verifySelectedItem();
2499
2500         // WARNING: BLACK MAGIC
2501         // See if there is a stack suited for our current guess.
2502         // If such stack does not exist, clear the guess.
2503         if(m_selected_content_guess.name != "" &&
2504                         selected.name == m_selected_content_guess.name &&
2505                         selected.count == m_selected_content_guess.count){
2506                 // Selected item fits the guess. Skip the black magic.
2507         }
2508         else if(m_selected_content_guess.name != ""){
2509                 bool found = false;
2510                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2511                         const ListDrawSpec &s = m_inventorylists[i];
2512                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2513                         if(!inv)
2514                                 continue;
2515                         InventoryList *list = inv->getList(s.listname);
2516                         if(!list)
2517                                 continue;
2518                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2519                                 u32 item_i = i + s.start_item_i;
2520                                 if(item_i >= list->getSize())
2521                                         continue;
2522                                 ItemStack stack = list->getItem(item_i);
2523                                 if(stack.name == m_selected_content_guess.name &&
2524                                                 stack.count == m_selected_content_guess.count){
2525                                         found = true;
2526                                         infostream<<"Client: Changing selected content guess to "
2527                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2528                                                         <<" "<<item_i<<std::endl;
2529                                         delete m_selected_item;
2530                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2531                                         m_selected_amount = stack.count;
2532                                 }
2533                         }
2534                 }
2535                 if(!found){
2536                         infostream<<"Client: Discarding selected content guess: "
2537                                         <<m_selected_content_guess.getItemString()<<std::endl;
2538                         m_selected_content_guess.name = "";
2539                 }
2540         }
2541
2542         // If craftresult is nonempty and nothing else is selected, select it now.
2543         if(!m_selected_item)
2544         {
2545                 for(u32 i=0; i<m_inventorylists.size(); i++)
2546                 {
2547                         const ListDrawSpec &s = m_inventorylists[i];
2548                         if(s.listname == "craftpreview")
2549                         {
2550                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2551                                 InventoryList *list = inv->getList("craftresult");
2552                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2553                                 {
2554                                         m_selected_item = new ItemSpec;
2555                                         m_selected_item->inventoryloc = s.inventoryloc;
2556                                         m_selected_item->listname = "craftresult";
2557                                         m_selected_item->i = 0;
2558                                         m_selected_amount = 0;
2559                                         m_selected_dragging = false;
2560                                         break;
2561                                 }
2562                         }
2563                 }
2564         }
2565
2566         // If craftresult is selected, keep the whole stack selected
2567         if(m_selected_item && m_selected_item->listname == "craftresult")
2568         {
2569                 m_selected_amount = verifySelectedItem().count;
2570         }
2571 }
2572
2573 ItemStack GUIFormSpecMenu::verifySelectedItem()
2574 {
2575         // If the selected stack has become empty for some reason, deselect it.
2576         // If the selected stack has become inaccessible, deselect it.
2577         // If the selected stack has become smaller, adjust m_selected_amount.
2578         // Return the selected stack.
2579
2580         if(m_selected_item)
2581         {
2582                 if(m_selected_item->isValid())
2583                 {
2584                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2585                         if(inv)
2586                         {
2587                                 InventoryList *list = inv->getList(m_selected_item->listname);
2588                                 if(list && (u32) m_selected_item->i < list->getSize())
2589                                 {
2590                                         ItemStack stack = list->getItem(m_selected_item->i);
2591                                         if(m_selected_amount > stack.count)
2592                                                 m_selected_amount = stack.count;
2593                                         if(!stack.empty())
2594                                                 return stack;
2595                                 }
2596                         }
2597                 }
2598
2599                 // selection was not valid
2600                 delete m_selected_item;
2601                 m_selected_item = NULL;
2602                 m_selected_amount = 0;
2603                 m_selected_dragging = false;
2604         }
2605         return ItemStack();
2606 }
2607
2608 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2609 {
2610         if(m_text_dst)
2611         {
2612                 std::map<std::string, std::string> fields;
2613
2614                 if (quitmode == quit_mode_accept) {
2615                         fields["quit"] = "true";
2616                 }
2617
2618                 if (quitmode == quit_mode_cancel) {
2619                         fields["quit"] = "true";
2620                         m_text_dst->gotText(fields);
2621                         return;
2622                 }
2623
2624                 if (current_keys_pending.key_down) {
2625                         fields["key_down"] = "true";
2626                         current_keys_pending.key_down = false;
2627                 }
2628
2629                 if (current_keys_pending.key_up) {
2630                         fields["key_up"] = "true";
2631                         current_keys_pending.key_up = false;
2632                 }
2633
2634                 if (current_keys_pending.key_enter) {
2635                         fields["key_enter"] = "true";
2636                         current_keys_pending.key_enter = false;
2637                 }
2638
2639                 if (current_keys_pending.key_escape) {
2640                         fields["key_escape"] = "true";
2641                         current_keys_pending.key_escape = false;
2642                 }
2643
2644                 for(unsigned int i=0; i<m_fields.size(); i++) {
2645                         const FieldSpec &s = m_fields[i];
2646                         if(s.send) {
2647                                 std::string name  = wide_to_narrow(s.fname);
2648                                 if(s.ftype == f_Button) {
2649                                         fields[name] = wide_to_narrow(s.flabel);
2650                                 }
2651                                 else if(s.ftype == f_Table) {
2652                                         GUITable *table = getTable(s.fname);
2653                                         if (table) {
2654                                                 fields[name] = table->checkEvent();
2655                                         }
2656                                 }
2657                                 else if(s.ftype == f_DropDown) {
2658                                         // no dynamic cast possible due to some distributions shipped
2659                                         // without rtti support in irrlicht
2660                                         IGUIElement * element = getElementFromId(s.fid);
2661                                         gui::IGUIComboBox *e = NULL;
2662                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2663                                                 e = static_cast<gui::IGUIComboBox*>(element);
2664                                         }
2665                                         s32 selected = e->getSelected();
2666                                         if (selected >= 0) {
2667                                                 fields[name] =
2668                                                         wide_to_narrow(e->getItem(selected));
2669                                         }
2670                                 }
2671                                 else if (s.ftype == f_TabHeader) {
2672                                         // no dynamic cast possible due to some distributions shipped
2673                                         // without rtti support in irrlicht
2674                                         IGUIElement * element = getElementFromId(s.fid);
2675                                         gui::IGUITabControl *e = NULL;
2676                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2677                                                 e = static_cast<gui::IGUITabControl*>(element);
2678                                         }
2679
2680                                         if (e != 0) {
2681                                                 std::stringstream ss;
2682                                                 ss << (e->getActiveTab() +1);
2683                                                 fields[name] = ss.str();
2684                                         }
2685                                 }
2686                                 else if (s.ftype == f_CheckBox) {
2687                                         // no dynamic cast possible due to some distributions shipped
2688                                         // without rtti support in irrlicht
2689                                         IGUIElement * element = getElementFromId(s.fid);
2690                                         gui::IGUICheckBox *e = NULL;
2691                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2692                                                 e = static_cast<gui::IGUICheckBox*>(element);
2693                                         }
2694
2695                                         if (e != 0) {
2696                                                 if (e->isChecked())
2697                                                         fields[name] = "true";
2698                                                 else
2699                                                         fields[name] = "false";
2700                                         }
2701                                 }
2702                                 else if (s.ftype == f_ScrollBar) {
2703                                         // no dynamic cast possible due to some distributions shipped
2704                                         // without rtti support in irrlicht
2705                                         IGUIElement * element = getElementFromId(s.fid);
2706                                         gui::IGUIScrollBar *e = NULL;
2707                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
2708                                                 e = static_cast<gui::IGUIScrollBar*>(element);
2709                                         }
2710
2711                                         if (e != 0) {
2712                                                 std::stringstream os;
2713                                                 os << e->getPos();
2714                                                 if (s.fdefault == L"Changed")
2715                                                         fields[name] = "CHG:" + os.str();
2716                                                 else
2717                                                         fields[name] = "VAL:" + os.str();
2718                                         }
2719                                 }
2720                                 else
2721                                 {
2722                                         IGUIElement* e = getElementFromId(s.fid);
2723                                         if(e != NULL) {
2724                                                 fields[name] = wide_to_narrow(e->getText());
2725                                         }
2726                                 }
2727                         }
2728                 }
2729
2730                 m_text_dst->gotText(fields);
2731         }
2732 }
2733
2734 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2735 {
2736         while(tocheck != NULL) {
2737                 if (tocheck == parent) {
2738                         return true;
2739                 }
2740                 tocheck = tocheck->getParent();
2741         }
2742         return false;
2743 }
2744
2745 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2746 {
2747         // The IGUITabControl renders visually using the skin's selected
2748         // font, which we override for the duration of form drawing,
2749         // but computes tab hotspots based on how it would have rendered
2750         // using the font that is selected at the time of button release.
2751         // To make these two consistent, temporarily override the skin's
2752         // font while the IGUITabControl is processing the event.
2753         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
2754                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2755                 s32 x = event.MouseInput.X;
2756                 s32 y = event.MouseInput.Y;
2757                 gui::IGUIElement *hovered =
2758                         Environment->getRootGUIElement()->getElementFromPoint(
2759                                 core::position2d<s32>(x, y));
2760                 if (hovered && isMyChild(hovered) &&
2761                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
2762                         gui::IGUISkin* skin = Environment->getSkin();
2763                         assert(skin != NULL);
2764                         gui::IGUIFont *old_font = skin->getFont();
2765                         skin->setFont(m_font);
2766                         bool retval = hovered->OnEvent(event);
2767                         skin->setFont(old_font);
2768                         return retval;
2769                 }
2770         }
2771
2772         // Fix Esc/Return key being eaten by checkboxen and tables
2773         if(event.EventType==EET_KEY_INPUT_EVENT) {
2774                 KeyPress kp(event.KeyInput);
2775                 if (kp == EscapeKey || kp == CancelKey
2776                                 || kp == getKeySetting("keymap_inventory")
2777                                 || event.KeyInput.Key==KEY_RETURN) {
2778                         gui::IGUIElement *focused = Environment->getFocus();
2779                         if (focused && isMyChild(focused) &&
2780                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2781                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2782                                 OnEvent(event);
2783                                 return true;
2784                         }
2785                 }
2786         }
2787         // Mouse wheel events: send to hovered element instead of focused
2788         if(event.EventType==EET_MOUSE_INPUT_EVENT
2789                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
2790                 s32 x = event.MouseInput.X;
2791                 s32 y = event.MouseInput.Y;
2792                 gui::IGUIElement *hovered =
2793                         Environment->getRootGUIElement()->getElementFromPoint(
2794                                 core::position2d<s32>(x, y));
2795                 if (hovered && isMyChild(hovered)) {
2796                         hovered->OnEvent(event);
2797                         return true;
2798                 }
2799         }
2800
2801         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
2802                 s32 x = event.MouseInput.X;
2803                 s32 y = event.MouseInput.Y;
2804                 gui::IGUIElement *hovered =
2805                         Environment->getRootGUIElement()->getElementFromPoint(
2806                                 core::position2d<s32>(x, y));
2807                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2808                         m_old_tooltip_id = -1;
2809                         m_old_tooltip = "";
2810                 }
2811                 if (!isChild(hovered,this)) {
2812                         if (DoubleClickDetection(event)) {
2813                                 return true;
2814                         }
2815                 }
2816         }
2817
2818         #ifdef __ANDROID__
2819         // display software keyboard when clicking edit boxes
2820         if (event.EventType == EET_MOUSE_INPUT_EVENT
2821                         && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2822                 gui::IGUIElement *hovered =
2823                         Environment->getRootGUIElement()->getElementFromPoint(
2824                                 core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
2825                 if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) {
2826                         bool retval = hovered->OnEvent(event);
2827                         if (retval) {
2828                                 Environment->setFocus(hovered);
2829                         }
2830                         m_JavaDialogFieldName = getNameByID(hovered->getID());
2831                         std::string message   = gettext("Enter ");
2832                         std::string label     = wide_to_narrow(getLabelByID(hovered->getID()));
2833                         if (label == "") {
2834                                 label = "text";
2835                         }
2836                         message += gettext(label) + ":";
2837
2838                         /* single line text input */
2839                         int type = 2;
2840
2841                         /* multi line text input */
2842                         if (((gui::IGUIEditBox*) hovered)->isMultiLineEnabled()) {
2843                                 type = 1;
2844                         }
2845
2846                         /* passwords are always single line */
2847                         if (((gui::IGUIEditBox*) hovered)->isPasswordBox()) {
2848                                 type = 3;
2849                         }
2850
2851                         porting::showInputDialog(gettext("ok"), "",
2852                                         wide_to_narrow(((gui::IGUIEditBox*) hovered)->getText()),
2853                                         type);
2854                         return retval;
2855                 }
2856         }
2857
2858         if (event.EventType == EET_TOUCH_INPUT_EVENT)
2859         {
2860                 SEvent translated;
2861                 memset(&translated, 0, sizeof(SEvent));
2862                 translated.EventType   = EET_MOUSE_INPUT_EVENT;
2863                 gui::IGUIElement* root = Environment->getRootGUIElement();
2864
2865                 if (!root) {
2866                         errorstream
2867                         << "GUIFormSpecMenu::preprocessEvent unable to get root element"
2868                         << std::endl;
2869                         return false;
2870                 }
2871                 gui::IGUIElement* hovered = root->getElementFromPoint(
2872                         core::position2d<s32>(
2873                                         event.TouchInput.X,
2874                                         event.TouchInput.Y));
2875
2876                 translated.MouseInput.X = event.TouchInput.X;
2877                 translated.MouseInput.Y = event.TouchInput.Y;
2878                 translated.MouseInput.Control = false;
2879
2880                 bool dont_send_event = false;
2881
2882                 if (event.TouchInput.touchedCount == 1) {
2883                         switch (event.TouchInput.Event) {
2884                                 case ETIE_PRESSED_DOWN:
2885                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2886                                         translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN;
2887                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2888                                         m_down_pos = m_pointer;
2889                                         break;
2890                                 case ETIE_MOVED:
2891                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
2892                                         translated.MouseInput.Event = EMIE_MOUSE_MOVED;
2893                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2894                                         break;
2895                                 case ETIE_LEFT_UP:
2896                                         translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP;
2897                                         translated.MouseInput.ButtonStates = 0;
2898                                         hovered = root->getElementFromPoint(m_down_pos);
2899                                         /* we don't have a valid pointer element use last
2900                                          * known pointer pos */
2901                                         translated.MouseInput.X = m_pointer.X;
2902                                         translated.MouseInput.Y = m_pointer.Y;
2903
2904                                         /* reset down pos */
2905                                         m_down_pos = v2s32(0,0);
2906                                         break;
2907                                 default:
2908                                         dont_send_event = true;
2909                                         //this is not supposed to happen
2910                                         errorstream
2911                                         << "GUIFormSpecMenu::preprocessEvent unexpected usecase Event="
2912                                         << event.TouchInput.Event << std::endl;
2913                         }
2914                 } else if ( (event.TouchInput.touchedCount == 2) &&
2915                                 (event.TouchInput.Event == ETIE_PRESSED_DOWN) ) {
2916                         hovered = root->getElementFromPoint(m_down_pos);
2917
2918                         translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
2919                         translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT;
2920                         translated.MouseInput.X = m_pointer.X;
2921                         translated.MouseInput.Y = m_pointer.Y;
2922
2923                         if (hovered) {
2924                                 hovered->OnEvent(translated);
2925                         }
2926
2927                         translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP;
2928                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
2929
2930
2931                         if (hovered) {
2932                                 hovered->OnEvent(translated);
2933                         }
2934                         dont_send_event = true;
2935                 }
2936                 /* ignore unhandled 2 touch events ... accidental moving for example */
2937                 else if (event.TouchInput.touchedCount == 2) {
2938                         dont_send_event = true;
2939                 }
2940                 else if (event.TouchInput.touchedCount > 2) {
2941                         errorstream
2942                         << "GUIFormSpecMenu::preprocessEvent to many multitouch events "
2943                         << event.TouchInput.touchedCount << " ignoring them" << std::endl;
2944                 }
2945
2946                 if (dont_send_event) {
2947                         return true;
2948                 }
2949
2950                 /* check if translated event needs to be preprocessed again */
2951                 if (preprocessEvent(translated)) {
2952                         return true;
2953                 }
2954                 if (hovered) {
2955                         grab();
2956                         bool retval = hovered->OnEvent(translated);
2957
2958                         if (event.TouchInput.Event == ETIE_LEFT_UP) {
2959                                 /* reset pointer */
2960                                 m_pointer = v2s32(0,0);
2961                         }
2962                         drop();
2963                         return retval;
2964                 }
2965         }
2966         #endif
2967
2968         return false;
2969 }
2970
2971 /******************************************************************************/
2972 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
2973 {
2974         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2975                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
2976                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
2977
2978                 m_doubleclickdetect[1].pos  = m_pointer;
2979                 m_doubleclickdetect[1].time = getTimeMs();
2980         }
2981         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2982                 u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs());
2983                 if (delta > 400) {
2984                         return false;
2985                 }
2986
2987                 double squaredistance =
2988                                 m_doubleclickdetect[0].pos
2989                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
2990
2991                 if (squaredistance > (30*30)) {
2992                         return false;
2993                 }
2994
2995                 SEvent* translated = new SEvent();
2996                 assert(translated != 0);
2997                 //translate doubleclick to escape
2998                 memset(translated, 0, sizeof(SEvent));
2999                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3000                 translated->KeyInput.Key         = KEY_ESCAPE;
3001                 translated->KeyInput.Control     = false;
3002                 translated->KeyInput.Shift       = false;
3003                 translated->KeyInput.PressedDown = true;
3004                 translated->KeyInput.Char        = 0;
3005                 OnEvent(*translated);
3006
3007                 // no need to send the key up event as we're already deleted
3008                 // and no one else did notice this event
3009                 delete translated;
3010                 return true;
3011         }
3012         return false;
3013 }
3014
3015 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3016 {
3017         if(event.EventType==EET_KEY_INPUT_EVENT) {
3018                 KeyPress kp(event.KeyInput);
3019                 if (event.KeyInput.PressedDown && ( (kp == EscapeKey) ||
3020                         (kp == getKeySetting("keymap_inventory")) || (kp == CancelKey))) {
3021                         if (m_allowclose) {
3022                                 doPause = false;
3023                                 acceptInput(quit_mode_cancel);
3024                                 quitMenu();
3025                         } else {
3026                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
3027                         }
3028                         return true;
3029                 } else if (m_client != NULL && event.KeyInput.PressedDown &&
3030                         (kp == getKeySetting("keymap_screenshot"))) {
3031                                 m_client->makeScreenshot(m_device);
3032                 }
3033                 if (event.KeyInput.PressedDown &&
3034                         (event.KeyInput.Key==KEY_RETURN ||
3035                          event.KeyInput.Key==KEY_UP ||
3036                          event.KeyInput.Key==KEY_DOWN)
3037                         ) {
3038                         switch (event.KeyInput.Key) {
3039                                 case KEY_RETURN:
3040                                         current_keys_pending.key_enter = true;
3041                                         break;
3042                                 case KEY_UP:
3043                                         current_keys_pending.key_up = true;
3044                                         break;
3045                                 case KEY_DOWN:
3046                                         current_keys_pending.key_down = true;
3047                                         break;
3048                                 break;
3049                                 default:
3050                                         //can't happen at all!
3051                                         assert("reached a source line that can't ever been reached" == 0);
3052                                         break;
3053                         }
3054                         if (current_keys_pending.key_enter && m_allowclose) {
3055                                 acceptInput(quit_mode_accept);
3056                                 quitMenu();
3057                         } else {
3058                                 acceptInput();
3059                         }
3060                         return true;
3061                 }
3062
3063         }
3064
3065         /* Mouse event other than movement, or crossing the border of inventory
3066           field while holding right mouse button
3067          */
3068         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3069                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3070                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3071                           event.MouseInput.isRightPressed() &&
3072                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3073
3074                 // Get selected item and hovered/clicked item (s)
3075
3076                 m_old_tooltip_id = -1;
3077                 updateSelectedItem();
3078                 ItemSpec s = getItemAtPos(m_pointer);
3079
3080                 Inventory *inv_selected = NULL;
3081                 Inventory *inv_s = NULL;
3082
3083                 if(m_selected_item) {
3084                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3085                         assert(inv_selected);
3086                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
3087                 }
3088
3089                 u32 s_count = 0;
3090
3091                 if(s.isValid())
3092                 do { // breakable
3093                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3094
3095                         if(!inv_s) {
3096                                 errorstream<<"InventoryMenu: The selected inventory location "
3097                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
3098                                                 <<std::endl;
3099                                 s.i = -1;  // make it invalid again
3100                                 break;
3101                         }
3102
3103                         InventoryList *list = inv_s->getList(s.listname);
3104                         if(list == NULL) {
3105                                 verbosestream<<"InventoryMenu: The selected inventory list \""
3106                                                 <<s.listname<<"\" does not exist"<<std::endl;
3107                                 s.i = -1;  // make it invalid again
3108                                 break;
3109                         }
3110
3111                         if((u32)s.i >= list->getSize()) {
3112                                 infostream<<"InventoryMenu: The selected inventory list \""
3113                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
3114                                                 <<list->getSize()<<")"<<std::endl;
3115                                 s.i = -1;  // make it invalid again
3116                                 break;
3117                         }
3118
3119                         s_count = list->getItem(s.i).count;
3120                 } while(0);
3121
3122                 bool identical = (m_selected_item != NULL) && s.isValid() &&
3123                         (inv_selected == inv_s) &&
3124                         (m_selected_item->listname == s.listname) &&
3125                         (m_selected_item->i == s.i);
3126
3127                 // buttons: 0 = left, 1 = right, 2 = middle
3128                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event, -1 movement
3129                 int button = 0;
3130                 int updown = 2;
3131                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
3132                         { button = 0; updown = 0; }
3133                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
3134                         { button = 1; updown = 0; }
3135                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
3136                         { button = 2; updown = 0; }
3137                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
3138                         { button = 0; updown = 1; }
3139                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
3140                         { button = 1; updown = 1; }
3141                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
3142                         { button = 2; updown = 1; }
3143                 else if(event.MouseInput.Event == EMIE_MOUSE_MOVED)
3144                         { updown = -1;}
3145
3146                 // Set this number to a positive value to generate a move action
3147                 // from m_selected_item to s.
3148                 u32 move_amount = 0;
3149
3150                 // Set this number to a positive value to generate a drop action
3151                 // from m_selected_item.
3152                 u32 drop_amount = 0;
3153
3154                 // Set this number to a positive value to generate a craft action at s.
3155                 u32 craft_amount = 0;
3156
3157                 if(updown == 0) {
3158                         // Some mouse button has been pressed
3159
3160                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3161                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3162
3163                         m_selected_dragging = false;
3164
3165                         if(s.isValid() && s.listname == "craftpreview") {
3166                                 // Craft preview has been clicked: craft
3167                                 craft_amount = (button == 2 ? 10 : 1);
3168                         }
3169                         else if(m_selected_item == NULL) {
3170                                 if(s_count != 0) {
3171                                         // Non-empty stack has been clicked: select it
3172                                         m_selected_item = new ItemSpec(s);
3173
3174                                         if(button == 1)  // right
3175                                                 m_selected_amount = (s_count + 1) / 2;
3176                                         else if(button == 2)  // middle
3177                                                 m_selected_amount = MYMIN(s_count, 10);
3178                                         else  // left
3179                                                 m_selected_amount = s_count;
3180
3181                                         m_selected_dragging = true;
3182                                         m_rmouse_auto_place = false;
3183                                 }
3184                         }
3185                         else { // m_selected_item != NULL
3186                                 assert(m_selected_amount >= 1);
3187
3188                                 if(s.isValid()) {
3189                                         // Clicked a slot: move
3190                                         if(button == 1)  // right
3191                                                 move_amount = 1;
3192                                         else if(button == 2)  // middle
3193                                                 move_amount = MYMIN(m_selected_amount, 10);
3194                                         else  // left
3195                                                 move_amount = m_selected_amount;
3196
3197                                         if(identical) {
3198                                                 if(move_amount >= m_selected_amount)
3199                                                         m_selected_amount = 0;
3200                                                 else
3201                                                         m_selected_amount -= move_amount;
3202                                                 move_amount = 0;
3203                                         }
3204                                 }
3205                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3206                                         // Clicked outside of the window: drop
3207                                         if(button == 1)  // right
3208                                                 drop_amount = 1;
3209                                         else if(button == 2)  // middle
3210                                                 drop_amount = MYMIN(m_selected_amount, 10);
3211                                         else  // left
3212                                                 drop_amount = m_selected_amount;
3213                                 }
3214                         }
3215                 }
3216                 else if(updown == 1) {
3217                         // Some mouse button has been released
3218
3219                         //infostream<<"Mouse button "<<button<<" released at p=("
3220                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3221
3222                         if(m_selected_item != NULL && m_selected_dragging && s.isValid()) {
3223                                 if(!identical) {
3224                                         // Dragged to different slot: move all selected
3225                                         move_amount = m_selected_amount;
3226                                 }
3227                         }
3228                         else if(m_selected_item != NULL && m_selected_dragging &&
3229                                 !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
3230                                 // Dragged outside of window: drop all selected
3231                                 drop_amount = m_selected_amount;
3232                         }
3233
3234                         m_selected_dragging = false;
3235                         // Keep count of how many times right mouse button has been
3236                         // clicked. One click is drag without dropping. Click + release
3237                         // + click changes to drop one item when moved mode
3238                         if(button == 1 && m_selected_item != NULL)
3239                                 m_rmouse_auto_place = !m_rmouse_auto_place;
3240                 }
3241                 else if(updown == -1) {
3242                         // Mouse has been moved and rmb is down and mouse pointer just
3243                         // entered a new inventory field (checked in the entry-if, this
3244                         // is the only action here that is generated by mouse movement)
3245                         if(m_selected_item != NULL && s.isValid()){
3246                                 // Move 1 item
3247                                 // TODO: middle mouse to move 10 items might be handy
3248                                 if (m_rmouse_auto_place) {
3249                                         // Only move an item if the destination slot is empty
3250                                         // or contains the same item type as what is going to be
3251                                         // moved
3252                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3253                                         InventoryList *list_to = inv_s->getList(s.listname);
3254                                         assert(list_from && list_to);
3255                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3256                                         ItemStack stack_to = list_to->getItem(s.i);
3257                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3258                                                 move_amount = 1;
3259                                 }
3260                         }
3261                 }
3262
3263                 // Possibly send inventory action to server
3264                 if(move_amount > 0)
3265                 {
3266                         // Send IACTION_MOVE
3267
3268                         assert(m_selected_item && m_selected_item->isValid());
3269                         assert(s.isValid());
3270
3271                         assert(inv_selected && inv_s);
3272                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3273                         InventoryList *list_to = inv_s->getList(s.listname);
3274                         assert(list_from && list_to);
3275                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3276                         ItemStack stack_to = list_to->getItem(s.i);
3277
3278                         // Check how many items can be moved
3279                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3280                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
3281                         // If source stack cannot be added to destination stack at all,
3282                         // they are swapped
3283                         if ((leftover.count == stack_from.count) &&
3284                                         (leftover.name == stack_from.name)) {
3285                                 m_selected_amount = stack_to.count;
3286                                 // In case the server doesn't directly swap them but instead
3287                                 // moves stack_to somewhere else, set this
3288                                 m_selected_content_guess = stack_to;
3289                                 m_selected_content_guess_inventory = s.inventoryloc;
3290                         }
3291                         // Source stack goes fully into destination stack
3292                         else if(leftover.empty()) {
3293                                 m_selected_amount -= move_amount;
3294                                 m_selected_content_guess = ItemStack(); // Clear
3295                         }
3296                         // Source stack goes partly into destination stack
3297                         else {
3298                                 move_amount -= leftover.count;
3299                                 m_selected_amount -= move_amount;
3300                                 m_selected_content_guess = ItemStack(); // Clear
3301                         }
3302
3303                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
3304                         IMoveAction *a = new IMoveAction();
3305                         a->count = move_amount;
3306                         a->from_inv = m_selected_item->inventoryloc;
3307                         a->from_list = m_selected_item->listname;
3308                         a->from_i = m_selected_item->i;
3309                         a->to_inv = s.inventoryloc;
3310                         a->to_list = s.listname;
3311                         a->to_i = s.i;
3312                         m_invmgr->inventoryAction(a);
3313                 }
3314                 else if(drop_amount > 0) {
3315                         m_selected_content_guess = ItemStack(); // Clear
3316
3317                         // Send IACTION_DROP
3318
3319                         assert(m_selected_item && m_selected_item->isValid());
3320                         assert(inv_selected);
3321                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3322                         assert(list_from);
3323                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3324
3325                         // Check how many items can be dropped
3326                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3327                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3328                         m_selected_amount -= drop_amount;
3329
3330                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
3331                         IDropAction *a = new IDropAction();
3332                         a->count = drop_amount;
3333                         a->from_inv = m_selected_item->inventoryloc;
3334                         a->from_list = m_selected_item->listname;
3335                         a->from_i = m_selected_item->i;
3336                         m_invmgr->inventoryAction(a);
3337                 }
3338                 else if(craft_amount > 0) {
3339                         m_selected_content_guess = ItemStack(); // Clear
3340
3341                         // Send IACTION_CRAFT
3342
3343                         assert(s.isValid());
3344                         assert(inv_s);
3345
3346                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
3347                         ICraftAction *a = new ICraftAction();
3348                         a->count = craft_amount;
3349                         a->craft_inv = s.inventoryloc;
3350                         m_invmgr->inventoryAction(a);
3351                 }
3352
3353                 // If m_selected_amount has been decreased to zero, deselect
3354                 if(m_selected_amount == 0) {
3355                         delete m_selected_item;
3356                         m_selected_item = NULL;
3357                         m_selected_amount = 0;
3358                         m_selected_dragging = false;
3359                         m_selected_content_guess = ItemStack();
3360                 }
3361                 m_old_pointer = m_pointer;
3362         }
3363         if(event.EventType==EET_GUI_EVENT) {
3364
3365                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
3366                                 && isVisible()) {
3367                         // find the element that was clicked
3368                         for(unsigned int i=0; i<m_fields.size(); i++) {
3369                                 FieldSpec &s = m_fields[i];
3370                                 if ((s.ftype == f_TabHeader) &&
3371                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3372                                         s.send = true;
3373                                         acceptInput();
3374                                         s.send = false;
3375                                         return true;
3376                                 }
3377                         }
3378                 }
3379                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
3380                                 && isVisible()) {
3381                         if(!canTakeFocus(event.GUIEvent.Element)) {
3382                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
3383                                                 <<std::endl;
3384                                 // Returning true disables focus change
3385                                 return true;
3386                         }
3387                 }
3388                 if((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
3389                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
3390                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
3391                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
3392                         unsigned int btn_id = event.GUIEvent.Caller->getID();
3393
3394                         if (btn_id == 257) {
3395                                 if (m_allowclose) {
3396                                         acceptInput(quit_mode_accept);
3397                                         quitMenu();
3398                                 } else {
3399                                         acceptInput();
3400                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3401                                 }
3402                                 // quitMenu deallocates menu
3403                                 return true;
3404                         }
3405
3406                         // find the element that was clicked
3407                         for(u32 i=0; i<m_fields.size(); i++) {
3408                                 FieldSpec &s = m_fields[i];
3409                                 // if its a button, set the send field so
3410                                 // lua knows which button was pressed
3411                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
3412                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3413                                         s.send = true;
3414                                         if(s.is_exit) {
3415                                                 if (m_allowclose) {
3416                                                         acceptInput(quit_mode_accept);
3417                                                         quitMenu();
3418                                                 } else {
3419                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
3420                                                 }
3421                                                 return true;
3422                                         } else {
3423                                                 acceptInput(quit_mode_no);
3424                                                 s.send = false;
3425                                                 return true;
3426                                         }
3427                                 }
3428                                 else if ((s.ftype == f_DropDown) &&
3429                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3430                                         // only send the changed dropdown
3431                                         for(u32 i=0; i<m_fields.size(); i++) {
3432                                                 FieldSpec &s2 = m_fields[i];
3433                                                 if (s2.ftype == f_DropDown) {
3434                                                         s2.send = false;
3435                                                 }
3436                                         }
3437                                         s.send = true;
3438                                         acceptInput(quit_mode_no);
3439
3440                                         // revert configuration to make sure dropdowns are sent on
3441                                         // regular button click
3442                                         for(u32 i=0; i<m_fields.size(); i++) {
3443                                                 FieldSpec &s2 = m_fields[i];
3444                                                 if (s2.ftype == f_DropDown) {
3445                                                         s2.send = true;
3446                                                 }
3447                                         }
3448                                         return true;
3449                                 }
3450                                 else if ((s.ftype == f_ScrollBar) &&
3451                                         (s.fid == event.GUIEvent.Caller->getID()))
3452                                 {
3453                                         s.fdefault = L"Changed";
3454                                         acceptInput(quit_mode_no);
3455                                         s.fdefault = L"";
3456                                 }
3457                         }
3458                 }
3459
3460                 if(event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
3461                         if(event.GUIEvent.Caller->getID() > 257) {
3462
3463                                 if (m_allowclose) {
3464                                         acceptInput(quit_mode_accept);
3465                                         quitMenu();
3466                                 } else {
3467                                         current_keys_pending.key_enter = true;
3468                                         acceptInput();
3469                                 }
3470                                 // quitMenu deallocates menu
3471                                 return true;
3472                         }
3473                 }
3474
3475                 if(event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
3476                         int current_id = event.GUIEvent.Caller->getID();
3477                         if(current_id > 257) {
3478                                 // find the element that was clicked
3479                                 for(u32 i=0; i<m_fields.size(); i++) {
3480                                         FieldSpec &s = m_fields[i];
3481                                         // if it's a table, set the send field
3482                                         // so lua knows which table was changed
3483                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
3484                                                 s.send = true;
3485                                                 acceptInput();
3486                                                 s.send=false;
3487                                         }
3488                                 }
3489                                 return true;
3490                         }
3491                 }
3492         }
3493
3494         return Parent ? Parent->OnEvent(event) : false;
3495 }
3496
3497 /**
3498  * get name of element by element id
3499  * @param id of element
3500  * @return name string or empty string
3501  */
3502 std::wstring GUIFormSpecMenu::getNameByID(s32 id)
3503 {
3504         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3505                                 iter != m_fields.end(); iter++) {
3506                 if (iter->fid == id) {
3507                         return iter->fname;
3508                 }
3509         }
3510         return L"";
3511 }
3512
3513 /**
3514  * get label of element by id
3515  * @param id of element
3516  * @return label string or empty string
3517  */
3518 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
3519 {
3520         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
3521                                 iter != m_fields.end(); iter++) {
3522                 if (iter->fid == id) {
3523                         return iter->flabel;
3524                 }
3525         }
3526         return L"";
3527 }