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