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