Fix sqlite3 map shutdown fails due to missing to finalize list statement
[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
53 #define MY_CHECKPOS(a,b)                                                                                                        \
54         if (v_pos.size() != 2) {                                                                                                \
55                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
56                         << parts[b] << "\"" << std::endl;                                                               \
57                         return;                                                                                                                 \
58         }
59
60 #define MY_CHECKGEOM(a,b)                                                                                                       \
61         if (v_geom.size() != 2) {                                                                                               \
62                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
63                         << parts[b] << "\"" << std::endl;                                                               \
64                         return;                                                                                                                 \
65         }
66 /*
67         GUIFormSpecMenu
68 */
69
70 GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev,
71                 gui::IGUIElement* parent, s32 id, IMenuManager *menumgr,
72                 InventoryManager *invmgr, IGameDef *gamedef,
73                 ISimpleTextureSource *tsrc, IFormSource* fsrc, TextDest* tdst,
74                 GUIFormSpecMenu** ext_ptr) :
75         GUIModalMenu(dev->getGUIEnvironment(), parent, id, menumgr),
76         m_device(dev),
77         m_invmgr(invmgr),
78         m_gamedef(gamedef),
79         m_tsrc(tsrc),
80         m_selected_item(NULL),
81         m_selected_amount(0),
82         m_selected_dragging(false),
83         m_tooltip_element(NULL),
84         m_allowclose(true),
85         m_lock(false),
86         m_form_src(fsrc),
87         m_text_dst(tdst),
88         m_ext_ptr(ext_ptr),
89         m_font(dev->getGUIEnvironment()->getSkin()->getFont())
90 {
91         current_keys_pending.key_down = false;
92         current_keys_pending.key_up = false;
93         current_keys_pending.key_enter = false;
94         current_keys_pending.key_escape = false;
95
96         m_doubleclickdetect[0].time = 0;
97         m_doubleclickdetect[1].time = 0;
98
99         m_doubleclickdetect[0].pos = v2s32(0, 0);
100         m_doubleclickdetect[1].pos = v2s32(0, 0);
101
102         m_btn_height = g_settings->getS32("font_size") +2;
103         assert(m_btn_height > 0);
104 }
105
106 GUIFormSpecMenu::~GUIFormSpecMenu()
107 {
108         removeChildren();
109
110         for (u32 i = 0; i < m_tables.size(); ++i) {
111                 GUITable *table = m_tables[i].second;
112                 table->drop();
113         }
114
115         delete m_selected_item;
116
117         if (m_form_src != NULL) {
118                 delete m_form_src;
119         }
120         if (m_text_dst != NULL) {
121                 delete m_text_dst;
122         }
123
124         if (m_ext_ptr != NULL) {
125                 assert(*m_ext_ptr == this);
126                 *m_ext_ptr = NULL;
127         }
128 }
129
130 void GUIFormSpecMenu::removeChildren()
131 {
132         const core::list<gui::IGUIElement*> &children = getChildren();
133
134         while(!children.empty()) {
135                 (*children.getLast())->remove();
136         }
137
138         if(m_tooltip_element) {
139                 m_tooltip_element->remove();
140                 m_tooltip_element->drop();
141                 m_tooltip_element = NULL;
142         }
143
144 }
145
146 void GUIFormSpecMenu::setInitialFocus()
147 {
148         // Set initial focus according to following order of precedence:
149         // 1. first empty editbox
150         // 2. first editbox
151         // 3. first table
152         // 4. last button
153         // 5. first focusable (not statictext, not tabheader)
154         // 6. first child element
155
156         core::list<gui::IGUIElement*> children = getChildren();
157
158         // in case "children" contains any NULL elements, remove them
159         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
160                         it != children.end();) {
161                 if (*it)
162                         ++it;
163                 else
164                         it = children.erase(it);
165         }
166
167         // 1. first empty editbox
168         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
169                         it != children.end(); ++it) {
170                 if ((*it)->getType() == gui::EGUIET_EDIT_BOX
171                                 && (*it)->getText()[0] == 0) {
172                         Environment->setFocus(*it);
173                         return;
174                 }
175         }
176
177         // 2. first editbox
178         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
179                         it != children.end(); ++it) {
180                 if ((*it)->getType() == gui::EGUIET_EDIT_BOX) {
181                         Environment->setFocus(*it);
182                         return;
183                 }
184         }
185
186         // 3. first table
187         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
188                         it != children.end(); ++it) {
189                 if ((*it)->getTypeName() == std::string("GUITable")) {
190                         Environment->setFocus(*it);
191                         return;
192                 }
193         }
194
195         // 4. last button
196         for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
197                         it != children.end(); --it) {
198                 if ((*it)->getType() == gui::EGUIET_BUTTON) {
199                         Environment->setFocus(*it);
200                         return;
201                 }
202         }
203
204         // 5. first focusable (not statictext, not tabheader)
205         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
206                         it != children.end(); ++it) {
207                 if ((*it)->getType() != gui::EGUIET_STATIC_TEXT &&
208                                 (*it)->getType() != gui::EGUIET_TAB_CONTROL) {
209                         Environment->setFocus(*it);
210                         return;
211                 }
212         }
213
214         // 6. first child element
215         if (children.empty())
216                 Environment->setFocus(this);
217         else
218                 Environment->setFocus(*(children.begin()));
219 }
220
221 GUITable* GUIFormSpecMenu::getTable(std::wstring tablename)
222 {
223         for (u32 i = 0; i < m_tables.size(); ++i) {
224                 if (tablename == m_tables[i].first.fname)
225                         return m_tables[i].second;
226         }
227         return 0;
228 }
229
230 std::vector<std::string> split(const std::string &s, char delim) {
231         std::vector<std::string> tokens;
232
233         std::string current = "";
234         bool last_was_escape = false;
235         for(unsigned int i=0; i < s.size(); i++) {
236                 if (last_was_escape) {
237                         current += '\\';
238                         current += s.c_str()[i];
239                         last_was_escape = false;
240                 }
241                 else {
242                         if (s.c_str()[i] == delim) {
243                                 tokens.push_back(current);
244                                 current = "";
245                                 last_was_escape = false;
246                         }
247                         else if (s.c_str()[i] == '\\'){
248                                 last_was_escape = true;
249                         }
250                         else {
251                                 current += s.c_str()[i];
252                                 last_was_escape = false;
253                         }
254                 }
255         }
256         //push last element
257         tokens.push_back(current);
258
259         return tokens;
260 }
261
262 void GUIFormSpecMenu::parseSize(parserData* data,std::string element)
263 {
264         std::vector<std::string> parts = split(element,',');
265
266         if ((parts.size() == 2) || parts.size() == 3) {
267                 v2f invsize;
268
269                 if (parts[1].find(';') != std::string::npos)
270                         parts[1] = parts[1].substr(0,parts[1].find(';'));
271
272                 invsize.X = stof(parts[0]);
273                 invsize.Y = stof(parts[1]);
274
275                 lockSize(false);
276                 if (parts.size() == 3) {
277                         if (parts[2] == "true") {
278                                 lockSize(true,v2u32(800,600));
279                         }
280                 }
281
282                 double cur_scaling = porting::getDisplayDensity() *
283                                 g_settings->getFloat("gui_scaling");
284
285                 if (m_lock) {
286                         v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize();
287                         v2u32 delta = current_screensize - m_lockscreensize;
288
289                         if (current_screensize.Y > m_lockscreensize.Y)
290                                 delta.Y /= 2;
291                         else
292                                 delta.Y = 0;
293
294                         if (current_screensize.X > m_lockscreensize.X)
295                                 delta.X /= 2;
296                         else
297                                 delta.X = 0;
298
299                         offset = v2s32(delta.X,delta.Y);
300
301                         data->screensize = m_lockscreensize;
302
303                         // fixed scaling for fixed size gui elements */
304                         cur_scaling = LEGACY_SCALING;
305                 }
306                 else {
307                         offset = v2s32(0,0);
308                 }
309
310                 /* adjust image size to dpi */
311                 int y_partition = 15;
312                 imgsize = v2s32(data->screensize.Y/y_partition, data->screensize.Y/y_partition);
313                 int min_imgsize = DEFAULT_IMGSIZE * cur_scaling;
314                 while ((min_imgsize > imgsize.Y) && (y_partition > 1)) {
315                         y_partition--;
316                         imgsize = v2s32(data->screensize.Y/y_partition, data->screensize.Y/y_partition);
317                 }
318                 assert(y_partition > 0);
319
320                 /* adjust spacing to dpi */
321                 spacing = v2s32(imgsize.X+(DEFAULT_XSPACING * cur_scaling),
322                                 imgsize.Y+(DEFAULT_YSPACING * cur_scaling));
323
324                 padding = v2s32(data->screensize.Y/imgsize.Y, data->screensize.Y/imgsize.Y);
325
326                 /* adjust padding to dpi */
327                 padding = v2s32(
328                                 (padding.X/(2.0/3.0)) * cur_scaling,
329                                 (padding.X/(2.0/3.0)) * cur_scaling
330                                 );
331                 data->size = v2s32(
332                         padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
333                         padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + m_btn_height - 5
334                 );
335                 data->rect = core::rect<s32>(
336                                 data->screensize.X/2 - data->size.X/2 + offset.X,
337                                 data->screensize.Y/2 - data->size.Y/2 + offset.Y,
338                                 data->screensize.X/2 + data->size.X/2 + offset.X,
339                                 data->screensize.Y/2 + data->size.Y/2 + offset.Y
340                 );
341
342                 DesiredRect = data->rect;
343                 recalculateAbsolutePosition(false);
344                 data->basepos = getBasePos();
345                 data->bp_set = 2;
346                 return;
347         }
348         errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'"  << std::endl;
349 }
350
351 void GUIFormSpecMenu::parseList(parserData* data,std::string element)
352 {
353         if (m_gamedef == 0) {
354                 errorstream<<"WARNING: invalid use of 'list' with m_gamedef==0"<<std::endl;
355                 return;
356         }
357
358         std::vector<std::string> parts = split(element,';');
359
360         if ((parts.size() == 4) || (parts.size() == 5)) {
361                 std::string location = parts[0];
362                 std::string listname = parts[1];
363                 std::vector<std::string> v_pos  = split(parts[2],',');
364                 std::vector<std::string> v_geom = split(parts[3],',');
365                 std::string startindex = "";
366                 if (parts.size() == 5)
367                         startindex = parts[4];
368
369                 MY_CHECKPOS("list",2);
370                 MY_CHECKGEOM("list",3);
371
372                 InventoryLocation loc;
373
374                 if(location == "context" || location == "current_name")
375                         loc = m_current_inventory_location;
376                 else
377                         loc.deSerialize(location);
378
379                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
380                 pos.X += stof(v_pos[0]) * (float)spacing.X;
381                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
382
383                 v2s32 geom;
384                 geom.X = stoi(v_geom[0]);
385                 geom.Y = stoi(v_geom[1]);
386
387                 s32 start_i = 0;
388                 if(startindex != "")
389                         start_i = stoi(startindex);
390
391                 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
392                         errorstream<< "Invalid list element: '" << element << "'"  << std::endl;
393                         return;
394                 }
395
396                 if(data->bp_set != 2)
397                         errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
398                 m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
399                 return;
400         }
401         errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
402 }
403
404 void GUIFormSpecMenu::parseCheckbox(parserData* data,std::string element)
405 {
406         std::vector<std::string> parts = split(element,';');
407
408         if ((parts.size() >= 3) || (parts.size() <= 5)) {
409                 std::vector<std::string> v_pos = split(parts[0],',');
410                 std::string name = parts[1];
411                 std::string label = parts[2];
412                 std::string selected = "";
413
414                 if (parts.size() >= 4)
415                         selected = parts[3];
416
417                 MY_CHECKPOS("checkbox",0);
418
419                 v2s32 pos = padding;
420                 pos.X += stof(v_pos[0]) * (float) spacing.X;
421                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
422
423                 bool fselected = false;
424
425                 if (selected == "true")
426                         fselected = true;
427
428                 std::wstring wlabel = narrow_to_wide(label.c_str());
429
430                 core::rect<s32> rect = core::rect<s32>(
431                                 pos.X, pos.Y + ((imgsize.Y/2) - m_btn_height),
432                                 pos.X + m_font->getDimension(wlabel.c_str()).Width + 25, // text size + size of checkbox
433                                 pos.Y + ((imgsize.Y/2) + m_btn_height));
434
435                 FieldSpec spec(
436                                 narrow_to_wide(name.c_str()),
437                                 wlabel, //Needed for displaying text on MSVC
438                                 wlabel,
439                                 258+m_fields.size()
440                         );
441
442                 spec.ftype = f_CheckBox;
443                 gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this,
444                                         spec.fid, spec.flabel.c_str());
445
446                 if (spec.fname == data->focused_fieldname) {
447                         Environment->setFocus(e);
448                 }
449                 if (parts.size() >= 5)
450                         spec.tooltip = parts[4];
451                 m_checkboxes.push_back(std::pair<FieldSpec,gui::IGUICheckBox*>(spec,e));
452                 m_fields.push_back(spec);
453                 return;
454         }
455         errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
456 }
457
458 void GUIFormSpecMenu::parseImage(parserData* data,std::string element)
459 {
460         std::vector<std::string> parts = split(element,';');
461
462         if (parts.size() == 3) {
463                 std::vector<std::string> v_pos = split(parts[0],',');
464                 std::vector<std::string> v_geom = split(parts[1],',');
465                 std::string name = unescape_string(parts[2]);
466
467                 MY_CHECKPOS("image",0);
468                 MY_CHECKGEOM("image",1);
469
470                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
471                 pos.X += stof(v_pos[0]) * (float) spacing.X;
472                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
473
474                 v2s32 geom;
475                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
476                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
477
478                 if(data->bp_set != 2)
479                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
480                 m_images.push_back(ImageDrawSpec(name, pos, geom));
481                 return;
482         }
483
484         if (parts.size() == 2) {
485                 std::vector<std::string> v_pos = split(parts[0],',');
486                 std::string name = unescape_string(parts[1]);
487
488                 MY_CHECKPOS("image",0);
489
490                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
491                 pos.X += stof(v_pos[0]) * (float) spacing.X;
492                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
493
494                 if(data->bp_set != 2)
495                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
496                 m_images.push_back(ImageDrawSpec(name, pos));
497                 return;
498         }
499         errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
500 }
501
502 void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element)
503 {
504         std::vector<std::string> parts = split(element,';');
505
506         if (parts.size() == 3) {
507                 std::vector<std::string> v_pos = split(parts[0],',');
508                 std::vector<std::string> v_geom = split(parts[1],',');
509                 std::string name = parts[2];
510
511                 MY_CHECKPOS("itemimage",0);
512                 MY_CHECKGEOM("itemimage",1);
513
514                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
515                 pos.X += stof(v_pos[0]) * (float) spacing.X;
516                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
517
518                 v2s32 geom;
519                 geom.X = stoi(v_geom[0]) * (float)imgsize.X;
520                 geom.Y = stoi(v_geom[1]) * (float)imgsize.Y;
521
522                 if(data->bp_set != 2)
523                         errorstream<<"WARNING: invalid use of item_image without a size[] element"<<std::endl;
524                 m_itemimages.push_back(ImageDrawSpec(name, pos, geom));
525                 return;
526         }
527         errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
528 }
529
530 void GUIFormSpecMenu::parseButton(parserData* data,std::string element,
531                 std::string type)
532 {
533         std::vector<std::string> parts = split(element,';');
534
535         if (parts.size() == 4 || parts.size() == 5) {
536                 std::vector<std::string> v_pos = split(parts[0],',');
537                 std::vector<std::string> v_geom = split(parts[1],',');
538                 std::string name = parts[2];
539                 std::string label = parts[3];
540
541                 MY_CHECKPOS("button",0);
542                 MY_CHECKGEOM("button",1);
543
544                 v2s32 pos = padding;
545                 pos.X += stof(v_pos[0]) * (float)spacing.X;
546                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
547
548                 v2s32 geom;
549                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
550                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
551
552                 core::rect<s32> rect =
553                                 core::rect<s32>(pos.X, pos.Y - m_btn_height,
554                                                 pos.X + geom.X, pos.Y + m_btn_height);
555
556                 if(data->bp_set != 2)
557                         errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
558
559                 label = unescape_string(label);
560
561                 std::wstring wlabel = narrow_to_wide(label.c_str());
562
563                 FieldSpec spec(
564                         narrow_to_wide(name.c_str()),
565                         wlabel,
566                         L"",
567                         258+m_fields.size()
568                 );
569                 spec.ftype = f_Button;
570                 if(type == "button_exit")
571                         spec.is_exit = true;
572                 gui::IGUIButton* e = Environment->addButton(rect, this, spec.fid,
573                                 spec.flabel.c_str());
574
575                 if (spec.fname == data->focused_fieldname) {
576                         Environment->setFocus(e);
577                 }
578                 if (parts.size() >= 5)
579                         spec.tooltip = parts[4];
580
581                 m_fields.push_back(spec);
582                 return;
583         }
584         errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
585 }
586
587 void GUIFormSpecMenu::parseBackground(parserData* data,std::string element)
588 {
589         std::vector<std::string> parts = split(element,';');
590
591         if ((parts.size() == 3) || (parts.size() == 4)) {
592                 std::vector<std::string> v_pos = split(parts[0],',');
593                 std::vector<std::string> v_geom = split(parts[1],',');
594                 std::string name = unescape_string(parts[2]);
595
596                 MY_CHECKPOS("background",0);
597                 MY_CHECKGEOM("background",1);
598
599                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
600                 pos.X += stof(v_pos[0]) * (float)spacing.X - ((float)spacing.X-(float)imgsize.X)/2;
601                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - ((float)spacing.Y-(float)imgsize.Y)/2;
602
603                 v2s32 geom;
604                 geom.X = stof(v_geom[0]) * (float)spacing.X;
605                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
606
607                 if (parts.size() == 4) {
608                         m_clipbackground = is_yes(parts[3]);
609                         if (m_clipbackground) {
610                                 pos.X = stoi(v_pos[0]); //acts as offset
611                                 pos.Y = stoi(v_pos[1]); //acts as offset
612                         }
613                 }
614
615                 if(data->bp_set != 2)
616                         errorstream<<"WARNING: invalid use of background without a size[] element"<<std::endl;
617                 m_backgrounds.push_back(ImageDrawSpec(name, pos, geom));
618                 return;
619         }
620         errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
621 }
622
623 void GUIFormSpecMenu::parseTableOptions(parserData* data,std::string element)
624 {
625         std::vector<std::string> parts = split(element,';');
626
627         data->table_options.clear();
628         for (size_t i = 0; i < parts.size(); ++i) {
629                 // Parse table option
630                 std::string opt = unescape_string(parts[i]);
631                 data->table_options.push_back(GUITable::splitOption(opt));
632         }
633 }
634
635 void GUIFormSpecMenu::parseTableColumns(parserData* data,std::string element)
636 {
637         std::vector<std::string> parts = split(element,';');
638
639         data->table_columns.clear();
640         for (size_t i = 0; i < parts.size(); ++i) {
641                 std::vector<std::string> col_parts = split(parts[i],',');
642                 GUITable::TableColumn column;
643                 // Parse column type
644                 if (!col_parts.empty())
645                         column.type = col_parts[0];
646                 // Parse column options
647                 for (size_t j = 1; j < col_parts.size(); ++j) {
648                         std::string opt = unescape_string(col_parts[j]);
649                         column.options.push_back(GUITable::splitOption(opt));
650                 }
651                 data->table_columns.push_back(column);
652         }
653 }
654
655 void GUIFormSpecMenu::parseTable(parserData* data,std::string element)
656 {
657         std::vector<std::string> parts = split(element,';');
658
659         if ((parts.size() == 4) || (parts.size() == 5)) {
660                 std::vector<std::string> v_pos = split(parts[0],',');
661                 std::vector<std::string> v_geom = split(parts[1],',');
662                 std::string name = parts[2];
663                 std::vector<std::string> items = split(parts[3],',');
664                 std::string str_initial_selection = "";
665                 std::string str_transparent = "false";
666
667                 if (parts.size() >= 5)
668                         str_initial_selection = parts[4];
669
670                 MY_CHECKPOS("table",0);
671                 MY_CHECKGEOM("table",1);
672
673                 v2s32 pos = padding;
674                 pos.X += stof(v_pos[0]) * (float)spacing.X;
675                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
676
677                 v2s32 geom;
678                 geom.X = stof(v_geom[0]) * (float)spacing.X;
679                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
680
681
682                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
683
684                 std::wstring fname_w = narrow_to_wide(name.c_str());
685
686                 FieldSpec spec(
687                         fname_w,
688                         L"",
689                         L"",
690                         258+m_fields.size()
691                 );
692
693                 spec.ftype = f_Table;
694
695                 for (unsigned int i = 0; i < items.size(); ++i) {
696                         items[i] = unescape_string(items[i]);
697                 }
698
699                 //now really show table
700                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
701                                 m_tsrc);
702
703                 if (spec.fname == data->focused_fieldname) {
704                         Environment->setFocus(e);
705                 }
706
707                 e->setTable(data->table_options, data->table_columns, items);
708
709                 if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) {
710                         e->setDynamicData(data->table_dyndata[fname_w]);
711                 }
712
713                 if ((str_initial_selection != "") &&
714                                 (str_initial_selection != "0"))
715                         e->setSelected(stoi(str_initial_selection.c_str()));
716
717                 m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e));
718                 m_fields.push_back(spec);
719                 return;
720         }
721         errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'"  << std::endl;
722 }
723
724 void GUIFormSpecMenu::parseTextList(parserData* data,std::string element)
725 {
726         std::vector<std::string> parts = split(element,';');
727
728         if ((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) {
729                 std::vector<std::string> v_pos = split(parts[0],',');
730                 std::vector<std::string> v_geom = split(parts[1],',');
731                 std::string name = parts[2];
732                 std::vector<std::string> items = split(parts[3],',');
733                 std::string str_initial_selection = "";
734                 std::string str_transparent = "false";
735
736                 if (parts.size() >= 5)
737                         str_initial_selection = parts[4];
738
739                 if (parts.size() >= 6)
740                         str_transparent = parts[5];
741
742                 MY_CHECKPOS("textlist",0);
743                 MY_CHECKGEOM("textlist",1);
744
745                 v2s32 pos = padding;
746                 pos.X += stof(v_pos[0]) * (float)spacing.X;
747                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
748
749                 v2s32 geom;
750                 geom.X = stof(v_geom[0]) * (float)spacing.X;
751                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
752
753
754                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
755
756                 std::wstring fname_w = narrow_to_wide(name.c_str());
757
758                 FieldSpec spec(
759                         fname_w,
760                         L"",
761                         L"",
762                         258+m_fields.size()
763                 );
764
765                 spec.ftype = f_Table;
766
767                 for (unsigned int i = 0; i < items.size(); ++i) {
768                         items[i] = unescape_string(items[i]);
769                 }
770
771                 //now really show list
772                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
773                                 m_tsrc);
774
775                 if (spec.fname == data->focused_fieldname) {
776                         Environment->setFocus(e);
777                 }
778
779                 e->setTextList(items, is_yes(str_transparent));
780
781                 if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) {
782                         e->setDynamicData(data->table_dyndata[fname_w]);
783                 }
784
785                 if ((str_initial_selection != "") &&
786                                 (str_initial_selection != "0"))
787                         e->setSelected(stoi(str_initial_selection.c_str()));
788
789                 m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e));
790                 m_fields.push_back(spec);
791                 return;
792         }
793         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
794 }
795
796
797 void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element)
798 {
799         std::vector<std::string> parts = split(element,';');
800
801         if (parts.size() == 5) {
802                 std::vector<std::string> v_pos = split(parts[0],',');
803                 std::string name = parts[2];
804                 std::vector<std::string> items = split(parts[3],',');
805                 std::string str_initial_selection = "";
806                 str_initial_selection = parts[4];
807
808                 MY_CHECKPOS("dropdown",0);
809
810                 v2s32 pos = padding;
811                 pos.X += stof(v_pos[0]) * (float)spacing.X;
812                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
813
814                 s32 width = stof(parts[1]) * (float)spacing.Y;
815
816                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
817                                 pos.X + width, pos.Y + (m_btn_height * 2));
818
819                 std::wstring fname_w = narrow_to_wide(name.c_str());
820
821                 FieldSpec spec(
822                         fname_w,
823                         L"",
824                         L"",
825                         258+m_fields.size()
826                 );
827
828                 spec.ftype = f_DropDown;
829                 spec.send = true;
830
831                 //now really show list
832                 gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
833
834                 if (spec.fname == data->focused_fieldname) {
835                         Environment->setFocus(e);
836                 }
837
838                 for (unsigned int i=0; i < items.size(); i++) {
839                         e->addItem(narrow_to_wide(items[i]).c_str());
840                 }
841
842                 if (str_initial_selection != "")
843                         e->setSelected(stoi(str_initial_selection.c_str())-1);
844
845                 m_fields.push_back(spec);
846                 return;
847         }
848         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
849                                 << element << "'"  << std::endl;
850 }
851
852 void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element)
853 {
854         std::vector<std::string> parts = split(element,';');
855
856         if (parts.size() == 4) {
857                 std::vector<std::string> v_pos = split(parts[0],',');
858                 std::vector<std::string> v_geom = split(parts[1],',');
859                 std::string name = parts[2];
860                 std::string label = parts[3];
861
862                 MY_CHECKPOS("pwdfield",0);
863                 MY_CHECKGEOM("pwdfield",1);
864
865                 v2s32 pos;
866                 pos.X += stof(v_pos[0]) * (float)spacing.X;
867                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
868
869                 v2s32 geom;
870                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
871
872                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
873                 pos.Y -= m_btn_height;
874                 geom.Y = m_btn_height*2;
875
876                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
877
878                 label = unescape_string(label);
879
880                 std::wstring wlabel = narrow_to_wide(label.c_str());
881
882                 FieldSpec spec(
883                         narrow_to_wide(name.c_str()),
884                         wlabel,
885                         L"",
886                         258+m_fields.size()
887                         );
888
889                 spec.send = true;
890                 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
891
892                 if (spec.fname == data->focused_fieldname) {
893                         Environment->setFocus(e);
894                 }
895
896                 if (label.length() >= 1)
897                 {
898                         rect.UpperLeftCorner.Y -= m_btn_height;
899                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + m_btn_height;
900                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
901                 }
902
903                 e->setPasswordBox(true,L'*');
904
905                 irr::SEvent evt;
906                 evt.EventType            = EET_KEY_INPUT_EVENT;
907                 evt.KeyInput.Key         = KEY_END;
908                 evt.KeyInput.Char        = 0;
909                 evt.KeyInput.Control     = 0;
910                 evt.KeyInput.Shift       = 0;
911                 evt.KeyInput.PressedDown = true;
912                 e->OnEvent(evt);
913                 m_fields.push_back(spec);
914                 return;
915         }
916         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
917 }
918
919 void GUIFormSpecMenu::parseSimpleField(parserData* data,
920                 std::vector<std::string> &parts)
921 {
922         std::string name = parts[0];
923         std::string label = parts[1];
924         std::string default_val = parts[2];
925
926         core::rect<s32> rect;
927
928         if(!data->bp_set)
929         {
930                 rect = core::rect<s32>(
931                         data->screensize.X/2 - 580/2,
932                         data->screensize.Y/2 - 300/2,
933                         data->screensize.X/2 + 580/2,
934                         data->screensize.Y/2 + 300/2
935                 );
936                 DesiredRect = rect;
937                 recalculateAbsolutePosition(false);
938                 data->basepos = getBasePos();
939                 data->bp_set = 1;
940         }
941         else if(data->bp_set == 2)
942                 errorstream<<"WARNING: invalid use of unpositioned \"field\" in inventory"<<std::endl;
943
944         v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
945         pos.Y = ((m_fields.size()+2)*60);
946         v2s32 size = DesiredRect.getSize();
947
948         rect = core::rect<s32>(size.X / 2 - 150, pos.Y,
949                         (size.X / 2 - 150) + 300, pos.Y + (m_btn_height*2));
950
951
952         if(m_form_src)
953                 default_val = m_form_src->resolveText(default_val);
954
955         default_val = unescape_string(default_val);
956         label = unescape_string(label);
957
958         std::wstring wlabel = narrow_to_wide(label.c_str());
959
960         FieldSpec spec(
961                 narrow_to_wide(name.c_str()),
962                 wlabel,
963                 narrow_to_wide(default_val.c_str()),
964                 258+m_fields.size()
965         );
966
967         if (name == "")
968         {
969                 // spec field id to 0, this stops submit searching for a value that isn't there
970                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
971         }
972         else
973         {
974                 spec.send = true;
975                 gui::IGUIEditBox *e =
976                         Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
977
978                 if (spec.fname == data->focused_fieldname) {
979                         Environment->setFocus(e);
980                 }
981
982                 irr::SEvent evt;
983                 evt.EventType            = EET_KEY_INPUT_EVENT;
984                 evt.KeyInput.Key         = KEY_END;
985                 evt.KeyInput.Char        = 0;
986                 evt.KeyInput.Control     = 0;
987                 evt.KeyInput.Shift       = 0;
988                 evt.KeyInput.PressedDown = true;
989                 e->OnEvent(evt);
990
991                 if (label.length() >= 1)
992                 {
993                         rect.UpperLeftCorner.Y -= m_btn_height;
994                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + m_btn_height;
995                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
996                 }
997         }
998
999         m_fields.push_back(spec);
1000 }
1001
1002 void GUIFormSpecMenu::parseTextArea(parserData* data,
1003                 std::vector<std::string>& parts,std::string type)
1004 {
1005
1006         std::vector<std::string> v_pos = split(parts[0],',');
1007         std::vector<std::string> v_geom = split(parts[1],',');
1008         std::string name = parts[2];
1009         std::string label = parts[3];
1010         std::string default_val = parts[4];
1011
1012         MY_CHECKPOS(type,0);
1013         MY_CHECKGEOM(type,1);
1014
1015         v2s32 pos;
1016         pos.X = stof(v_pos[0]) * (float) spacing.X;
1017         pos.Y = stof(v_pos[1]) * (float) spacing.Y;
1018
1019         v2s32 geom;
1020
1021         geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1022
1023         if (type == "textarea")
1024         {
1025                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1026                 pos.Y += m_btn_height;
1027         }
1028         else
1029         {
1030                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1031                 pos.Y -= m_btn_height;
1032                 geom.Y = m_btn_height*2;
1033         }
1034
1035         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1036
1037         if(data->bp_set != 2)
1038                 errorstream<<"WARNING: invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1039
1040         if(m_form_src)
1041                 default_val = m_form_src->resolveText(default_val);
1042
1043
1044         default_val = unescape_string(default_val);
1045         label = unescape_string(label);
1046
1047         std::wstring wlabel = narrow_to_wide(label.c_str());
1048
1049         FieldSpec spec(
1050                 narrow_to_wide(name.c_str()),
1051                 wlabel,
1052                 narrow_to_wide(default_val.c_str()),
1053                 258+m_fields.size()
1054         );
1055
1056         if (name == "")
1057         {
1058                 // spec field id to 0, this stops submit searching for a value that isn't there
1059                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1060         }
1061         else
1062         {
1063                 spec.send = true;
1064                 gui::IGUIEditBox *e =
1065                         Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
1066
1067                 if (spec.fname == data->focused_fieldname) {
1068                         Environment->setFocus(e);
1069                 }
1070
1071                 if (type == "textarea")
1072                 {
1073                         e->setMultiLine(true);
1074                         e->setWordWrap(true);
1075                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1076                 } else {
1077                         irr::SEvent evt;
1078                         evt.EventType            = EET_KEY_INPUT_EVENT;
1079                         evt.KeyInput.Key         = KEY_END;
1080                         evt.KeyInput.Char        = 0;
1081                         evt.KeyInput.Control     = 0;
1082                         evt.KeyInput.Shift       = 0;
1083                         evt.KeyInput.PressedDown = true;
1084                         e->OnEvent(evt);
1085                 }
1086
1087                 if (label.length() >= 1)
1088                 {
1089                         rect.UpperLeftCorner.Y -= m_btn_height;
1090                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + m_btn_height;
1091                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
1092                 }
1093         }
1094         m_fields.push_back(spec);
1095 }
1096
1097 void GUIFormSpecMenu::parseField(parserData* data,std::string element,
1098                 std::string type)
1099 {
1100         std::vector<std::string> parts = split(element,';');
1101
1102         if (parts.size() == 3 || parts.size() == 4) {
1103                 parseSimpleField(data,parts);
1104                 return;
1105         }
1106
1107         if (parts.size() == 5) {
1108                 parseTextArea(data,parts,type);
1109                 return;
1110         }
1111         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1112 }
1113
1114 void GUIFormSpecMenu::parseLabel(parserData* data,std::string element)
1115 {
1116         std::vector<std::string> parts = split(element,';');
1117
1118         if (parts.size() == 2) {
1119                 std::vector<std::string> v_pos = split(parts[0],',');
1120                 std::string text = parts[1];
1121
1122                 MY_CHECKPOS("label",0);
1123
1124                 v2s32 pos = padding;
1125                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1126                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1127
1128                 if(data->bp_set != 2)
1129                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1130
1131                 text = unescape_string(text);
1132
1133                 std::wstring wlabel = narrow_to_wide(text.c_str());
1134
1135                 core::rect<s32> rect = core::rect<s32>(
1136                                 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1137                                 pos.X + m_font->getDimension(wlabel.c_str()).Width,
1138                                 pos.Y+((imgsize.Y/2) + m_btn_height));
1139
1140                 FieldSpec spec(
1141                         L"",
1142                         wlabel,
1143                         L"",
1144                         258+m_fields.size()
1145                 );
1146                 Environment->addStaticText(spec.flabel.c_str(), rect, false, false, this, spec.fid);
1147                 m_fields.push_back(spec);
1148                 return;
1149         }
1150         errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'"  << std::endl;
1151 }
1152
1153 void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element)
1154 {
1155         std::vector<std::string> parts = split(element,';');
1156
1157         if (parts.size() == 2) {
1158                 std::vector<std::string> v_pos = split(parts[0],',');
1159                 std::wstring text = narrow_to_wide(unescape_string(parts[1]));
1160
1161                 MY_CHECKPOS("vertlabel",1);
1162
1163                 v2s32 pos = padding;
1164                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1165                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1166
1167                 core::rect<s32> rect = core::rect<s32>(
1168                                 pos.X, pos.Y+((imgsize.Y/2)- m_btn_height),
1169                                 pos.X+15, pos.Y +
1170                                         (m_font->getKerningHeight() +
1171                                         m_font->getDimension(text.c_str()).Height)
1172                                         * (text.length()+1));
1173                 //actually text.length() would be correct but adding +1 avoids to break all mods
1174
1175                 if(data->bp_set != 2)
1176                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1177
1178                 std::wstring label = L"";
1179
1180                 for (unsigned int i=0; i < text.length(); i++) {
1181                         label += text[i];
1182                         label += L"\n";
1183                 }
1184
1185                 FieldSpec spec(
1186                         L"",
1187                         label,
1188                         L"",
1189                         258+m_fields.size()
1190                 );
1191                 gui::IGUIStaticText *t =
1192                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, false, this, spec.fid);
1193                 t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1194                 m_fields.push_back(spec);
1195                 return;
1196         }
1197         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1198 }
1199
1200 void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element,
1201                 std::string type)
1202 {
1203         std::vector<std::string> parts = split(element,';');
1204
1205         if (((parts.size() >= 5) && (parts.size() <= 9)) && (parts.size() != 6)) {
1206                 std::vector<std::string> v_pos = split(parts[0],',');
1207                 std::vector<std::string> v_geom = split(parts[1],',');
1208                 std::string image_name = parts[2];
1209                 std::string name = parts[3];
1210                 std::string label = parts[4];
1211
1212                 MY_CHECKPOS("imagebutton",0);
1213                 MY_CHECKGEOM("imagebutton",1);
1214
1215                 v2s32 pos = padding;
1216                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1217                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1218                 v2s32 geom;
1219                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1220                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1221
1222                 bool noclip     = false;
1223                 bool drawborder = true;
1224                 std::string pressed_image_name = "";
1225
1226                 if (parts.size() >= 7) {
1227                         if (parts[5] == "true")
1228                                 noclip = true;
1229                         if (parts[6] == "false")
1230                                 drawborder = false;
1231                 }
1232
1233                 if (parts.size() >= 8) {
1234                         pressed_image_name = parts[7];
1235                 }
1236
1237                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1238
1239                 if(data->bp_set != 2)
1240                         errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;
1241
1242                 image_name = unescape_string(image_name);
1243                 pressed_image_name = unescape_string(pressed_image_name);
1244                 label = unescape_string(label);
1245
1246                 std::wstring wlabel = narrow_to_wide(label.c_str());
1247
1248                 FieldSpec spec(
1249                         narrow_to_wide(name.c_str()),
1250                         wlabel,
1251                         narrow_to_wide(image_name.c_str()),
1252                         258+m_fields.size()
1253                 );
1254                 spec.ftype = f_Button;
1255                 if(type == "image_button_exit")
1256                         spec.is_exit = true;
1257
1258                 video::ITexture *texture = 0;
1259                 video::ITexture *pressed_texture = 0;
1260                 texture = m_tsrc->getTexture(image_name);
1261                 if (pressed_image_name != "")
1262                         pressed_texture = m_tsrc->getTexture(pressed_image_name);
1263                 else
1264                         pressed_texture = texture;
1265
1266                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1267
1268                 if (spec.fname == data->focused_fieldname) {
1269                         Environment->setFocus(e);
1270                 }
1271                 if (parts.size() >= 9)
1272                         spec.tooltip = parts[8];
1273
1274                 e->setUseAlphaChannel(true);
1275                 e->setImage(texture);
1276                 e->setPressedImage(pressed_texture);
1277                 e->setScaleImage(true);
1278                 e->setNotClipped(noclip);
1279                 e->setDrawBorder(drawborder);
1280
1281                 m_fields.push_back(spec);
1282                 return;
1283         }
1284
1285         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1286 }
1287
1288 void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element)
1289 {
1290         std::vector<std::string> parts = split(element,';');
1291
1292         if ((parts.size() == 4) || (parts.size() == 6)) {
1293                 std::vector<std::string> v_pos = split(parts[0],',');
1294                 std::string name = parts[1];
1295                 std::vector<std::string> buttons = split(parts[2],',');
1296                 std::string str_index = parts[3];
1297                 bool show_background = true;
1298                 bool show_border = true;
1299                 int tab_index = stoi(str_index) -1;
1300
1301                 MY_CHECKPOS("tabheader",0);
1302
1303                 if (parts.size() == 6) {
1304                         if (parts[4] == "true")
1305                                 show_background = false;
1306                         if (parts[5] == "false")
1307                                 show_border = false;
1308                 }
1309
1310                 FieldSpec spec(
1311                         narrow_to_wide(name.c_str()),
1312                         L"",
1313                         L"",
1314                         258+m_fields.size()
1315                 );
1316
1317                 spec.ftype = f_TabHeader;
1318
1319                 v2s32 pos(0,0);
1320                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1321                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - m_btn_height * 2;
1322                 v2s32 geom;
1323                 geom.X = data->screensize.Y;
1324                 geom.Y = m_btn_height*2;
1325
1326                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1327                                 pos.Y+geom.Y);
1328
1329                 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1330                                 show_background, show_border, spec.fid);
1331                 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1332                                 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1333                 e->setTabHeight(m_btn_height*2);
1334
1335                 if (spec.fname == data->focused_fieldname) {
1336                         Environment->setFocus(e);
1337                 }
1338
1339                 e->setNotClipped(true);
1340
1341                 for (unsigned int i=0; i< buttons.size(); i++) {
1342                         e->addTab(narrow_to_wide(buttons[i]).c_str(), -1);
1343                 }
1344
1345                 if ((tab_index >= 0) &&
1346                                 (buttons.size() < INT_MAX) &&
1347                                 (tab_index < (int) buttons.size()))
1348                         e->setActiveTab(tab_index);
1349
1350                 m_fields.push_back(spec);
1351                 return;
1352         }
1353         errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
1354                         << element << "'"  << std::endl;
1355 }
1356
1357 void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element)
1358 {
1359
1360         if (m_gamedef == 0) {
1361                 errorstream <<
1362                                 "WARNING: invalid use of item_image_button with m_gamedef==0"
1363                                 << std::endl;
1364                 return;
1365         }
1366
1367         std::vector<std::string> parts = split(element,';');
1368
1369         if (parts.size() == 5) {
1370                 std::vector<std::string> v_pos = split(parts[0],',');
1371                 std::vector<std::string> v_geom = split(parts[1],',');
1372                 std::string item_name = parts[2];
1373                 std::string name = parts[3];
1374                 std::string label = parts[4];
1375
1376                 MY_CHECKPOS("itemimagebutton",0);
1377                 MY_CHECKGEOM("itemimagebutton",1);
1378
1379                 v2s32 pos = padding;
1380                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1381                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1382                 v2s32 geom;
1383                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1384                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1385
1386                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1387
1388                 if(data->bp_set != 2)
1389                         errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl;
1390
1391                 IItemDefManager *idef = m_gamedef->idef();
1392                 ItemStack item;
1393                 item.deSerialize(item_name, idef);
1394                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
1395                 std::string tooltip = item.getDefinition(idef).description;
1396
1397                 label = unescape_string(label);
1398                 FieldSpec spec(
1399                         narrow_to_wide(name.c_str()),
1400                         narrow_to_wide(label.c_str()),
1401                         narrow_to_wide(item_name.c_str()),
1402                         258+m_fields.size()
1403                 );
1404
1405                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1406
1407                 if (spec.fname == data->focused_fieldname) {
1408                         Environment->setFocus(e);
1409                 }
1410
1411                 e->setUseAlphaChannel(true);
1412                 e->setImage(texture);
1413                 e->setPressedImage(texture);
1414                 e->setScaleImage(true);
1415                 spec.ftype = f_Button;
1416                 rect+=data->basepos-padding;
1417                 spec.rect=rect;
1418                 spec.tooltip = tooltip;
1419                 m_fields.push_back(spec);
1420                 return;
1421         }
1422         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1423 }
1424
1425 void GUIFormSpecMenu::parseBox(parserData* data,std::string element)
1426 {
1427         std::vector<std::string> parts = split(element,';');
1428
1429         if (parts.size() == 3) {
1430                 std::vector<std::string> v_pos = split(parts[0],',');
1431                 std::vector<std::string> v_geom = split(parts[1],',');
1432
1433                 MY_CHECKPOS("box",0);
1434                 MY_CHECKGEOM("box",1);
1435
1436                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
1437                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1438                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1439
1440                 v2s32 geom;
1441                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1442                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1443
1444                 video::SColor tmp_color;
1445
1446                 if (parseColor(parts[2], tmp_color, false)) {
1447                         BoxDrawSpec spec(pos, geom, tmp_color);
1448
1449                         m_boxes.push_back(spec);
1450                 }
1451                 else {
1452                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1453                 }
1454                 return;
1455         }
1456         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1457 }
1458
1459 void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element)
1460 {
1461         std::vector<std::string> parts = split(element,';');
1462
1463         if ((parts.size() == 1) || (parts.size() == 2)) {
1464                 parseColor(parts[0],m_bgcolor,false);
1465
1466                 if (parts.size() == 2) {
1467                         std::string fullscreen = parts[1];
1468                         m_bgfullscreen = is_yes(fullscreen);
1469                 }
1470                 return;
1471         }
1472         errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"  << std::endl;
1473 }
1474
1475 void GUIFormSpecMenu::parseListColors(parserData* data,std::string element)
1476 {
1477         std::vector<std::string> parts = split(element,';');
1478
1479         if ((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) {
1480                 parseColor(parts[0], m_slotbg_n, false);
1481                 parseColor(parts[1], m_slotbg_h, false);
1482
1483                 if (parts.size() >= 3) {
1484                         if (parseColor(parts[2], m_slotbordercolor, false)) {
1485                                 m_slotborder = true;
1486                         }
1487                 }
1488                 if (parts.size() == 5) {
1489                         video::SColor tmp_color;
1490
1491                         if (parseColor(parts[3], tmp_color, false))
1492                                 m_tooltip_element->setBackgroundColor(tmp_color);
1493                         if (parseColor(parts[4], tmp_color, false))
1494                                 m_tooltip_element->setOverrideColor(tmp_color);
1495                 }
1496                 return;
1497         }
1498         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1499 }
1500
1501 void GUIFormSpecMenu::parseElement(parserData* data,std::string element)
1502 {
1503         //some prechecks
1504         if (element == "")
1505                 return;
1506
1507         std::vector<std::string> parts = split(element,'[');
1508
1509         // ugly workaround to keep compatibility
1510         if (parts.size() > 2) {
1511                 if (trim(parts[0]) == "image") {
1512                         for (unsigned int i=2;i< parts.size(); i++) {
1513                                 parts[1] += "[" + parts[i];
1514                         }
1515                 }
1516                 else { return; }
1517         }
1518
1519         if (parts.size() < 2) {
1520                 return;
1521         }
1522
1523         std::string type = trim(parts[0]);
1524         std::string description = trim(parts[1]);
1525
1526         if (type == "size") {
1527                 parseSize(data,description);
1528                 return;
1529         }
1530
1531         if (type == "invsize") {
1532                 log_deprecated("Deprecated formspec element \"invsize\" is used");
1533                 parseSize(data,description);
1534                 return;
1535         }
1536
1537         if (type == "list") {
1538                 parseList(data,description);
1539                 return;
1540         }
1541
1542         if (type == "checkbox") {
1543                 parseCheckbox(data,description);
1544                 return;
1545         }
1546
1547         if (type == "image") {
1548                 parseImage(data,description);
1549                 return;
1550         }
1551
1552         if (type == "item_image") {
1553                 parseItemImage(data,description);
1554                 return;
1555         }
1556
1557         if ((type == "button") || (type == "button_exit")) {
1558                 parseButton(data,description,type);
1559                 return;
1560         }
1561
1562         if (type == "background") {
1563                 parseBackground(data,description);
1564                 return;
1565         }
1566
1567         if (type == "tableoptions"){
1568                 parseTableOptions(data,description);
1569                 return;
1570         }
1571
1572         if (type == "tablecolumns"){
1573                 parseTableColumns(data,description);
1574                 return;
1575         }
1576
1577         if (type == "table"){
1578                 parseTable(data,description);
1579                 return;
1580         }
1581
1582         if (type == "textlist"){
1583                 parseTextList(data,description);
1584                 return;
1585         }
1586
1587         if (type == "dropdown"){
1588                 parseDropDown(data,description);
1589                 return;
1590         }
1591
1592         if (type == "pwdfield") {
1593                 parsePwdField(data,description);
1594                 return;
1595         }
1596
1597         if ((type == "field") || (type == "textarea")){
1598                 parseField(data,description,type);
1599                 return;
1600         }
1601
1602         if (type == "label") {
1603                 parseLabel(data,description);
1604                 return;
1605         }
1606
1607         if (type == "vertlabel") {
1608                 parseVertLabel(data,description);
1609                 return;
1610         }
1611
1612         if (type == "item_image_button") {
1613                 parseItemImageButton(data,description);
1614                 return;
1615         }
1616
1617         if ((type == "image_button") || (type == "image_button_exit")) {
1618                 parseImageButton(data,description,type);
1619                 return;
1620         }
1621
1622         if (type == "tabheader") {
1623                 parseTabHeader(data,description);
1624                 return;
1625         }
1626
1627         if (type == "box") {
1628                 parseBox(data,description);
1629                 return;
1630         }
1631
1632         if (type == "bgcolor") {
1633                 parseBackgroundColor(data,description);
1634                 return;
1635         }
1636
1637         if (type == "listcolors") {
1638                 parseListColors(data,description);
1639                 return;
1640         }
1641
1642         // Ignore others
1643         infostream
1644                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1645                 <<std::endl;
1646 }
1647
1648
1649
1650 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1651 {
1652         /* useless to regenerate without a screensize */
1653         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
1654                 return;
1655         }
1656
1657         parserData mydata;
1658
1659         //preserve tables
1660         for (u32 i = 0; i < m_tables.size(); ++i) {
1661                 std::wstring tablename = m_tables[i].first.fname;
1662                 GUITable *table = m_tables[i].second;
1663                 mydata.table_dyndata[tablename] = table->getDynamicData();
1664         }
1665
1666         //preserve focus
1667         gui::IGUIElement *focused_element = Environment->getFocus();
1668         if (focused_element && focused_element->getParent() == this) {
1669                 s32 focused_id = focused_element->getID();
1670                 if (focused_id > 257) {
1671                         for (u32 i=0; i<m_fields.size(); i++) {
1672                                 if (m_fields[i].fid == focused_id) {
1673                                         mydata.focused_fieldname =
1674                                                 m_fields[i].fname;
1675                                         break;
1676                                 }
1677                         }
1678                 }
1679         }
1680
1681         // Remove children
1682         removeChildren();
1683
1684         for (u32 i = 0; i < m_tables.size(); ++i) {
1685                 GUITable *table = m_tables[i].second;
1686                 table->drop();
1687         }
1688
1689         mydata.size= v2s32(100,100);
1690         mydata.screensize = screensize;
1691
1692         // Base position of contents of form
1693         mydata.basepos = getBasePos();
1694
1695         // State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
1696         // Used to adjust form size automatically if needed
1697         // A proceed button is added if there is no size[] element
1698         mydata.bp_set = 0;
1699
1700
1701         /* Convert m_init_draw_spec to m_inventorylists */
1702
1703         m_inventorylists.clear();
1704         m_images.clear();
1705         m_backgrounds.clear();
1706         m_itemimages.clear();
1707         m_tables.clear();
1708         m_checkboxes.clear();
1709         m_fields.clear();
1710         m_boxes.clear();
1711
1712         // Set default values (fits old formspec values)
1713         m_bgcolor = video::SColor(140,0,0,0);
1714         m_bgfullscreen = false;
1715
1716         m_slotbg_n = video::SColor(255,128,128,128);
1717         m_slotbg_h = video::SColor(255,192,192,192);
1718
1719         m_slotbordercolor = video::SColor(200,0,0,0);
1720         m_slotborder = false;
1721
1722         m_clipbackground = false;
1723         // Add tooltip
1724         {
1725                 assert(m_tooltip_element == NULL);
1726                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
1727                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
1728                 m_tooltip_element->enableOverrideColor(true);
1729                 m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
1730                 m_tooltip_element->setDrawBackground(true);
1731                 m_tooltip_element->setDrawBorder(true);
1732                 m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
1733                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1734                 m_tooltip_element->setWordWrap(false);
1735                 //we're not parent so no autograb for this one!
1736                 m_tooltip_element->grab();
1737         }
1738
1739
1740         std::vector<std::string> elements = split(m_formspec_string,']');
1741         for (unsigned int i=0; i< elements.size(); i++) {
1742                 parseElement(&mydata,elements[i]);
1743         }
1744
1745         // If there's fields, add a Proceed button
1746         if (m_fields.size() && mydata.bp_set != 2) {
1747                 // if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
1748                 mydata.rect = core::rect<s32>(
1749                                 mydata.screensize.X/2 - 580/2,
1750                                 mydata.screensize.Y/2 - 300/2,
1751                                 mydata.screensize.X/2 + 580/2,
1752                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
1753                 );
1754                 DesiredRect = mydata.rect;
1755                 recalculateAbsolutePosition(false);
1756                 mydata.basepos = getBasePos();
1757
1758                 {
1759                         v2s32 pos = mydata.basepos;
1760                         pos.Y = ((m_fields.size()+2)*60);
1761
1762                         v2s32 size = DesiredRect.getSize();
1763                         mydata.rect =
1764                                         core::rect<s32>(size.X/2-70, pos.Y,
1765                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
1766                         wchar_t* text = wgettext("Proceed");
1767                         Environment->addButton(mydata.rect, this, 257, text);
1768                         delete[] text;
1769                 }
1770
1771         }
1772
1773         //set initial focus if parser didn't set it
1774         focused_element = Environment->getFocus();
1775         if (!focused_element
1776                         || !isMyChild(focused_element)
1777                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
1778                 setInitialFocus();
1779 }
1780
1781 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
1782 {
1783         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1784
1785         for(u32 i=0; i<m_inventorylists.size(); i++)
1786         {
1787                 const ListDrawSpec &s = m_inventorylists[i];
1788
1789                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1790                 {
1791                         s32 item_i = i + s.start_item_i;
1792                         s32 x = (i%s.geom.X) * spacing.X;
1793                         s32 y = (i/s.geom.X) * spacing.Y;
1794                         v2s32 p0(x,y);
1795                         core::rect<s32> rect = imgrect + s.pos + p0;
1796                         if(rect.isPointInside(p))
1797                         {
1798                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
1799                         }
1800                 }
1801         }
1802
1803         return ItemSpec(InventoryLocation(), "", -1);
1804 }
1805
1806 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
1807 {
1808         video::IVideoDriver* driver = Environment->getVideoDriver();
1809
1810         // Get font
1811         gui::IGUIFont *font = NULL;
1812         gui::IGUISkin* skin = Environment->getSkin();
1813         if (skin)
1814                 font = skin->getFont();
1815
1816         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
1817         if(!inv){
1818                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1819                                 <<"The inventory location "
1820                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
1821                                 <<std::endl;
1822                 return;
1823         }
1824         InventoryList *ilist = inv->getList(s.listname);
1825         if(!ilist){
1826                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1827                                 <<"The inventory list \""<<s.listname<<"\" @ \""
1828                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
1829                                 <<std::endl;
1830                 return;
1831         }
1832
1833         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1834
1835         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1836         {
1837                 s32 item_i = i + s.start_item_i;
1838                 if(item_i >= (s32) ilist->getSize())
1839                         break;
1840                 s32 x = (i%s.geom.X) * spacing.X;
1841                 s32 y = (i/s.geom.X) * spacing.Y;
1842                 v2s32 p(x,y);
1843                 core::rect<s32> rect = imgrect + s.pos + p;
1844                 ItemStack item;
1845                 if(ilist)
1846                         item = ilist->getItem(item_i);
1847
1848                 bool selected = m_selected_item
1849                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
1850                         && m_selected_item->listname == s.listname
1851                         && m_selected_item->i == item_i;
1852                 bool hovering = rect.isPointInside(m_pointer);
1853
1854                 if(phase == 0)
1855                 {
1856                         if(hovering)
1857                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
1858                         else
1859                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
1860                 }
1861
1862                 //Draw inv slot borders
1863                 if (m_slotborder) {
1864                         s32 x1 = rect.UpperLeftCorner.X;
1865                         s32 y1 = rect.UpperLeftCorner.Y;
1866                         s32 x2 = rect.LowerRightCorner.X;
1867                         s32 y2 = rect.LowerRightCorner.Y;
1868                         s32 border = 1;
1869                         driver->draw2DRectangle(m_slotbordercolor,
1870                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
1871                                                                 v2s32(x2 + border, y1)), NULL);
1872                         driver->draw2DRectangle(m_slotbordercolor,
1873                                 core::rect<s32>(v2s32(x1 - border, y2),
1874                                                                 v2s32(x2 + border, y2 + border)), NULL);
1875                         driver->draw2DRectangle(m_slotbordercolor,
1876                                 core::rect<s32>(v2s32(x1 - border, y1),
1877                                                                 v2s32(x1, y2)), NULL);
1878                         driver->draw2DRectangle(m_slotbordercolor,
1879                                 core::rect<s32>(v2s32(x2, y1),
1880                                                                 v2s32(x2 + border, y2)), NULL);
1881                 }
1882
1883                 if(phase == 1)
1884                 {
1885                         // Draw item stack
1886                         if(selected)
1887                         {
1888                                 item.takeItem(m_selected_amount);
1889                         }
1890                         if(!item.empty())
1891                         {
1892                                 drawItemStack(driver, font, item,
1893                                                 rect, &AbsoluteClippingRect, m_gamedef);
1894                         }
1895
1896                         // Draw tooltip
1897                         std::string tooltip_text = "";
1898                         if(hovering && !m_selected_item)
1899                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
1900                         if(tooltip_text != "")
1901                         {
1902                                 m_tooltip_element->setVisible(true);
1903                                 this->bringToFront(m_tooltip_element);
1904                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
1905                                 s32 tooltip_x = m_pointer.X + m_btn_height;
1906                                 s32 tooltip_y = m_pointer.Y + m_btn_height;
1907                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
1908                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
1909                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
1910                                                 core::position2d<s32>(tooltip_x, tooltip_y),
1911                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
1912                         }
1913                 }
1914         }
1915 }
1916
1917 void GUIFormSpecMenu::drawSelectedItem()
1918 {
1919         if(!m_selected_item)
1920                 return;
1921
1922         video::IVideoDriver* driver = Environment->getVideoDriver();
1923
1924         // Get font
1925         gui::IGUIFont *font = NULL;
1926         gui::IGUISkin* skin = Environment->getSkin();
1927         if (skin)
1928                 font = skin->getFont();
1929
1930         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
1931         assert(inv);
1932         InventoryList *list = inv->getList(m_selected_item->listname);
1933         assert(list);
1934         ItemStack stack = list->getItem(m_selected_item->i);
1935         stack.count = m_selected_amount;
1936
1937         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1938         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
1939         drawItemStack(driver, font, stack, rect, NULL, m_gamedef);
1940 }
1941
1942 void GUIFormSpecMenu::drawMenu()
1943 {
1944         if(m_form_src){
1945                 std::string newform = m_form_src->getForm();
1946                 if(newform != m_formspec_string){
1947                         m_formspec_string = newform;
1948                         regenerateGui(m_screensize_old);
1949                 }
1950         }
1951
1952         m_pointer = m_device->getCursorControl()->getPosition();
1953
1954         updateSelectedItem();
1955
1956         gui::IGUISkin* skin = Environment->getSkin();
1957         if (!skin)
1958                 return;
1959         video::IVideoDriver* driver = Environment->getVideoDriver();
1960
1961         v2u32 screenSize = driver->getScreenSize();
1962         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
1963         if (m_bgfullscreen)
1964                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
1965         else
1966                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
1967
1968         m_tooltip_element->setVisible(false);
1969
1970         /*
1971                 Draw backgrounds
1972         */
1973         for(u32 i=0; i<m_backgrounds.size(); i++)
1974         {
1975                 const ImageDrawSpec &spec = m_backgrounds[i];
1976                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
1977
1978                 if (texture != 0) {
1979                         // Image size on screen
1980                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
1981                         // Image rectangle on screen
1982                         core::rect<s32> rect = imgrect + spec.pos;
1983
1984                         if (m_clipbackground) {
1985                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
1986                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
1987                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
1988                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
1989                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
1990                         }
1991
1992                         const video::SColor color(255,255,255,255);
1993                         const video::SColor colors[] = {color,color,color,color};
1994                         driver->draw2DImage(texture, rect,
1995                                 core::rect<s32>(core::position2d<s32>(0,0),
1996                                                 core::dimension2di(texture->getOriginalSize())),
1997                                 NULL/*&AbsoluteClippingRect*/, colors, true);
1998                 }
1999                 else {
2000                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2001                         errorstream << "\t" << spec.name << std::endl;
2002                 }
2003         }
2004
2005         /*
2006                 Draw Boxes
2007         */
2008         for(u32 i=0; i<m_boxes.size(); i++)
2009         {
2010                 const BoxDrawSpec &spec = m_boxes[i];
2011
2012                 irr::video::SColor todraw = spec.color;
2013
2014                 todraw.setAlpha(140);
2015
2016                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2017                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2018
2019                 driver->draw2DRectangle(todraw, rect, 0);
2020         }
2021         /*
2022                 Draw images
2023         */
2024         for(u32 i=0; i<m_images.size(); i++)
2025         {
2026                 const ImageDrawSpec &spec = m_images[i];
2027                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2028
2029                 if (texture != 0) {
2030                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2031                         // Image size on screen
2032                         core::rect<s32> imgrect;
2033
2034                         if (spec.scale)
2035                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2036                         else {
2037
2038                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2039                         }
2040                         // Image rectangle on screen
2041                         core::rect<s32> rect = imgrect + spec.pos;
2042                         const video::SColor color(255,255,255,255);
2043                         const video::SColor colors[] = {color,color,color,color};
2044                         driver->draw2DImage(texture, rect,
2045                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2046                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2047                 }
2048                 else {
2049                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2050                         errorstream << "\t" << spec.name << std::endl;
2051                 }
2052         }
2053
2054         /*
2055                 Draw item images
2056         */
2057         for(u32 i=0; i<m_itemimages.size(); i++)
2058         {
2059                 if (m_gamedef == 0)
2060                         break;
2061
2062                 const ImageDrawSpec &spec = m_itemimages[i];
2063                 IItemDefManager *idef = m_gamedef->idef();
2064                 ItemStack item;
2065                 item.deSerialize(spec.name, idef);
2066                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
2067                 // Image size on screen
2068                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2069                 // Image rectangle on screen
2070                 core::rect<s32> rect = imgrect + spec.pos;
2071                 const video::SColor color(255,255,255,255);
2072                 const video::SColor colors[] = {color,color,color,color};
2073                 driver->draw2DImage(texture, rect,
2074                         core::rect<s32>(core::position2d<s32>(0,0),
2075                                         core::dimension2di(texture->getOriginalSize())),
2076                         NULL/*&AbsoluteClippingRect*/, colors, true);
2077         }
2078
2079         /*
2080                 Draw items
2081                 Phase 0: Item slot rectangles
2082                 Phase 1: Item images; prepare tooltip
2083         */
2084         int start_phase=0;
2085         for(int phase=start_phase; phase<=1; phase++)
2086         for(u32 i=0; i<m_inventorylists.size(); i++)
2087         {
2088                 drawList(m_inventorylists[i], phase);
2089         }
2090
2091         /*
2092                 Call base class
2093         */
2094         gui::IGUIElement::draw();
2095
2096         /*
2097                 Draw fields/buttons tooltips
2098         */
2099         gui::IGUIElement *hovered =
2100                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2101
2102         if (hovered != NULL) {
2103                 s32 id = hovered->getID();
2104                 for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2105                                         iter != m_fields.end(); iter++) {
2106                         if ( (iter->fid == id) && (iter->tooltip != "") ) {
2107                                 m_tooltip_element->setVisible(true);
2108                                 this->bringToFront(m_tooltip_element);
2109                                 m_tooltip_element->setText(narrow_to_wide(iter->tooltip).c_str());
2110                                 s32 tooltip_x = m_pointer.X + m_btn_height;
2111                                 s32 tooltip_y = m_pointer.Y + m_btn_height;
2112                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2113                                 if (tooltip_x + tooltip_width > (s32)screenSize.X)
2114                                         tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
2115                                 int lines_count = 1;
2116                                 size_t i = 0;
2117                                 while ((i = iter->tooltip.find("\n", i)) != std::string::npos) {
2118                                         lines_count++;
2119                                         i += 2;
2120                                 }
2121                                 s32 tooltip_height = m_tooltip_element->getTextHeight() * lines_count + 5;
2122                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2123                                 core::position2d<s32>(tooltip_x, tooltip_y),
2124                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2125                                 break;
2126                         }
2127                 }
2128         }
2129
2130         /*
2131                 Draw dragged item stack
2132         */
2133         drawSelectedItem();
2134 }
2135
2136 void GUIFormSpecMenu::updateSelectedItem()
2137 {
2138         // If the selected stack has become empty for some reason, deselect it.
2139         // If the selected stack has become inaccessible, deselect it.
2140         // If the selected stack has become smaller, adjust m_selected_amount.
2141         ItemStack selected = verifySelectedItem();
2142
2143         // WARNING: BLACK MAGIC
2144         // See if there is a stack suited for our current guess.
2145         // If such stack does not exist, clear the guess.
2146         if(m_selected_content_guess.name != "" &&
2147                         selected.name == m_selected_content_guess.name &&
2148                         selected.count == m_selected_content_guess.count){
2149                 // Selected item fits the guess. Skip the black magic.
2150         }
2151         else if(m_selected_content_guess.name != ""){
2152                 bool found = false;
2153                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2154                         const ListDrawSpec &s = m_inventorylists[i];
2155                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2156                         if(!inv)
2157                                 continue;
2158                         InventoryList *list = inv->getList(s.listname);
2159                         if(!list)
2160                                 continue;
2161                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2162                                 u32 item_i = i + s.start_item_i;
2163                                 if(item_i >= list->getSize())
2164                                         continue;
2165                                 ItemStack stack = list->getItem(item_i);
2166                                 if(stack.name == m_selected_content_guess.name &&
2167                                                 stack.count == m_selected_content_guess.count){
2168                                         found = true;
2169                                         infostream<<"Client: Changing selected content guess to "
2170                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2171                                                         <<" "<<item_i<<std::endl;
2172                                         delete m_selected_item;
2173                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2174                                         m_selected_amount = stack.count;
2175                                 }
2176                         }
2177                 }
2178                 if(!found){
2179                         infostream<<"Client: Discarding selected content guess: "
2180                                         <<m_selected_content_guess.getItemString()<<std::endl;
2181                         m_selected_content_guess.name = "";
2182                 }
2183         }
2184
2185         // If craftresult is nonempty and nothing else is selected, select it now.
2186         if(!m_selected_item)
2187         {
2188                 for(u32 i=0; i<m_inventorylists.size(); i++)
2189                 {
2190                         const ListDrawSpec &s = m_inventorylists[i];
2191                         if(s.listname == "craftpreview")
2192                         {
2193                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2194                                 InventoryList *list = inv->getList("craftresult");
2195                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2196                                 {
2197                                         m_selected_item = new ItemSpec;
2198                                         m_selected_item->inventoryloc = s.inventoryloc;
2199                                         m_selected_item->listname = "craftresult";
2200                                         m_selected_item->i = 0;
2201                                         m_selected_amount = 0;
2202                                         m_selected_dragging = false;
2203                                         break;
2204                                 }
2205                         }
2206                 }
2207         }
2208
2209         // If craftresult is selected, keep the whole stack selected
2210         if(m_selected_item && m_selected_item->listname == "craftresult")
2211         {
2212                 m_selected_amount = verifySelectedItem().count;
2213         }
2214 }
2215
2216 ItemStack GUIFormSpecMenu::verifySelectedItem()
2217 {
2218         // If the selected stack has become empty for some reason, deselect it.
2219         // If the selected stack has become inaccessible, deselect it.
2220         // If the selected stack has become smaller, adjust m_selected_amount.
2221         // Return the selected stack.
2222
2223         if(m_selected_item)
2224         {
2225                 if(m_selected_item->isValid())
2226                 {
2227                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2228                         if(inv)
2229                         {
2230                                 InventoryList *list = inv->getList(m_selected_item->listname);
2231                                 if(list && (u32) m_selected_item->i < list->getSize())
2232                                 {
2233                                         ItemStack stack = list->getItem(m_selected_item->i);
2234                                         if(m_selected_amount > stack.count)
2235                                                 m_selected_amount = stack.count;
2236                                         if(!stack.empty())
2237                                                 return stack;
2238                                 }
2239                         }
2240                 }
2241
2242                 // selection was not valid
2243                 delete m_selected_item;
2244                 m_selected_item = NULL;
2245                 m_selected_amount = 0;
2246                 m_selected_dragging = false;
2247         }
2248         return ItemStack();
2249 }
2250
2251 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2252 {
2253         if(m_text_dst)
2254         {
2255                 std::map<std::string, std::string> fields;
2256
2257                 if (quitmode == quit_mode_accept) {
2258                         fields["quit"] = "true";
2259                 }
2260
2261                 if (quitmode == quit_mode_cancel) {
2262                         fields["quit"] = "true";
2263                         m_text_dst->gotText(fields);
2264                         return;
2265                 }
2266
2267                 if (current_keys_pending.key_down) {
2268                         fields["key_down"] = "true";
2269                         current_keys_pending.key_down = false;
2270                 }
2271
2272                 if (current_keys_pending.key_up) {
2273                         fields["key_up"] = "true";
2274                         current_keys_pending.key_up = false;
2275                 }
2276
2277                 if (current_keys_pending.key_enter) {
2278                         fields["key_enter"] = "true";
2279                         current_keys_pending.key_enter = false;
2280                 }
2281
2282                 if (current_keys_pending.key_escape) {
2283                         fields["key_escape"] = "true";
2284                         current_keys_pending.key_escape = false;
2285                 }
2286
2287                 for(unsigned int i=0; i<m_fields.size(); i++) {
2288                         const FieldSpec &s = m_fields[i];
2289                         if(s.send) {
2290                                 std::string name  = wide_to_narrow(s.fname);
2291                                 if(s.ftype == f_Button) {
2292                                         fields[name] = wide_to_narrow(s.flabel);
2293                                 }
2294                                 else if(s.ftype == f_Table) {
2295                                         GUITable *table = getTable(s.fname);
2296                                         if (table) {
2297                                                 fields[name] = table->checkEvent();
2298                                         }
2299                                 }
2300                                 else if(s.ftype == f_DropDown) {
2301                                         // no dynamic cast possible due to some distributions shipped
2302                                         // without rtti support in irrlicht
2303                                         IGUIElement * element = getElementFromId(s.fid);
2304                                         gui::IGUIComboBox *e = NULL;
2305                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2306                                                 e = static_cast<gui::IGUIComboBox*>(element);
2307                                         }
2308                                         s32 selected = e->getSelected();
2309                                         if (selected >= 0) {
2310                                                 fields[name] =
2311                                                         wide_to_narrow(e->getItem(selected));
2312                                         }
2313                                 }
2314                                 else if (s.ftype == f_TabHeader) {
2315                                         // no dynamic cast possible due to some distributions shipped
2316                                         // without rtti support in irrlicht
2317                                         IGUIElement * element = getElementFromId(s.fid);
2318                                         gui::IGUITabControl *e = NULL;
2319                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2320                                                 e = static_cast<gui::IGUITabControl*>(element);
2321                                         }
2322
2323                                         if (e != 0) {
2324                                                 std::stringstream ss;
2325                                                 ss << (e->getActiveTab() +1);
2326                                                 fields[name] = ss.str();
2327                                         }
2328                                 }
2329                                 else if (s.ftype == f_CheckBox) {
2330                                         // no dynamic cast possible due to some distributions shipped
2331                                         // without rtti support in irrlicht
2332                                         IGUIElement * element = getElementFromId(s.fid);
2333                                         gui::IGUICheckBox *e = NULL;
2334                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2335                                                 e = static_cast<gui::IGUICheckBox*>(element);
2336                                         }
2337
2338                                         if (e != 0) {
2339                                                 if (e->isChecked())
2340                                                         fields[name] = "true";
2341                                                 else
2342                                                         fields[name] = "false";
2343                                         }
2344                                 }
2345                                 else
2346                                 {
2347                                         IGUIElement* e = getElementFromId(s.fid);
2348                                         if(e != NULL) {
2349                                                 fields[name] = wide_to_narrow(e->getText());
2350                                         }
2351                                 }
2352                         }
2353                 }
2354
2355                 m_text_dst->gotText(fields);
2356         }
2357 }
2358
2359 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2360 {
2361         while(tocheck != NULL) {
2362                 if (tocheck == parent) {
2363                         return true;
2364                 }
2365                 tocheck = tocheck->getParent();
2366         }
2367         return false;
2368 }
2369
2370 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2371 {
2372         // Fix Esc/Return key being eaten by checkboxen and tables
2373         if(event.EventType==EET_KEY_INPUT_EVENT) {
2374                 KeyPress kp(event.KeyInput);
2375                 if (kp == EscapeKey || kp == getKeySetting("keymap_inventory")
2376                                 || event.KeyInput.Key==KEY_RETURN) {
2377                         gui::IGUIElement *focused = Environment->getFocus();
2378                         if (focused && isMyChild(focused) &&
2379                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2380                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2381                                 OnEvent(event);
2382                                 return true;
2383                         }
2384                 }
2385         }
2386         // Mouse wheel events: send to hovered element instead of focused
2387         if(event.EventType==EET_MOUSE_INPUT_EVENT
2388                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
2389                 s32 x = event.MouseInput.X;
2390                 s32 y = event.MouseInput.Y;
2391                 gui::IGUIElement *hovered =
2392                         Environment->getRootGUIElement()->getElementFromPoint(
2393                                 core::position2d<s32>(x, y));
2394                 if (hovered && isMyChild(hovered)) {
2395                         hovered->OnEvent(event);
2396                         return true;
2397                 }
2398         }
2399
2400         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
2401                 s32 x = event.MouseInput.X;
2402                 s32 y = event.MouseInput.Y;
2403                 gui::IGUIElement *hovered =
2404                         Environment->getRootGUIElement()->getElementFromPoint(
2405                                 core::position2d<s32>(x, y));
2406
2407                 if (!isChild(hovered,this)) {
2408                         if (DoubleClickDetection(event)) {
2409                                 return true;
2410                         }
2411                 }
2412         }
2413
2414         return false;
2415 }
2416
2417 /******************************************************************************/
2418 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
2419 {
2420         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
2421                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
2422                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
2423
2424                 m_doubleclickdetect[1].pos  = m_pointer;
2425                 m_doubleclickdetect[1].time = getTimeMs();
2426         }
2427         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2428                 u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs());
2429                 if (delta > 400) {
2430                         return false;
2431                 }
2432
2433                 double squaredistance =
2434                                 m_doubleclickdetect[0].pos
2435                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
2436
2437                 if (squaredistance > (30*30)) {
2438                         return false;
2439                 }
2440
2441                 SEvent* translated = new SEvent();
2442                 assert(translated != 0);
2443                 //translate doubleclick to escape
2444                 memset(translated, 0, sizeof(SEvent));
2445                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
2446                 translated->KeyInput.Key         = KEY_ESCAPE;
2447                 translated->KeyInput.Control     = false;
2448                 translated->KeyInput.Shift       = false;
2449                 translated->KeyInput.PressedDown = true;
2450                 translated->KeyInput.Char        = 0;
2451                 OnEvent(*translated);
2452
2453                 // no need to send the key up event as we're already deleted
2454                 // and no one else did notice this event
2455                 delete translated;
2456                 return true;
2457         }
2458         return false;
2459 }
2460
2461 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
2462 {
2463         if(event.EventType==EET_KEY_INPUT_EVENT) {
2464                 KeyPress kp(event.KeyInput);
2465                 if (event.KeyInput.PressedDown && (kp == EscapeKey ||
2466                         kp == getKeySetting("keymap_inventory"))) {
2467                         if (m_allowclose) {
2468                                 doPause = false;
2469                                 acceptInput(quit_mode_cancel);
2470                                 quitMenu();
2471                         } else {
2472                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
2473                         }
2474                         return true;
2475                 }
2476                 if (event.KeyInput.PressedDown &&
2477                         (event.KeyInput.Key==KEY_RETURN ||
2478                          event.KeyInput.Key==KEY_UP ||
2479                          event.KeyInput.Key==KEY_DOWN)
2480                         ) {
2481                         switch (event.KeyInput.Key) {
2482                                 case KEY_RETURN:
2483                                         current_keys_pending.key_enter = true;
2484                                         break;
2485                                 case KEY_UP:
2486                                         current_keys_pending.key_up = true;
2487                                         break;
2488                                 case KEY_DOWN:
2489                                         current_keys_pending.key_down = true;
2490                                         break;
2491                                 break;
2492                                 default:
2493                                         //can't happen at all!
2494                                         assert("reached a source line that can't ever been reached" == 0);
2495                                         break;
2496                         }
2497                         if (current_keys_pending.key_enter && m_allowclose) {
2498                                 acceptInput(quit_mode_accept);
2499                                 quitMenu();
2500                         } else {
2501                                 acceptInput();
2502                         }
2503                         return true;
2504                 }
2505
2506         }
2507         if(event.EventType==EET_MOUSE_INPUT_EVENT
2508                         && event.MouseInput.Event != EMIE_MOUSE_MOVED) {
2509                 // Mouse event other than movement
2510
2511                 // Get selected item and hovered/clicked item (s)
2512
2513                 updateSelectedItem();
2514                 ItemSpec s = getItemAtPos(m_pointer);
2515
2516                 Inventory *inv_selected = NULL;
2517                 Inventory *inv_s = NULL;
2518
2519                 if(m_selected_item) {
2520                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
2521                         assert(inv_selected);
2522                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
2523                 }
2524
2525                 u32 s_count = 0;
2526
2527                 if(s.isValid())
2528                 do { // breakable
2529                         inv_s = m_invmgr->getInventory(s.inventoryloc);
2530
2531                         if(!inv_s) {
2532                                 errorstream<<"InventoryMenu: The selected inventory location "
2533                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2534                                                 <<std::endl;
2535                                 s.i = -1;  // make it invalid again
2536                                 break;
2537                         }
2538
2539                         InventoryList *list = inv_s->getList(s.listname);
2540                         if(list == NULL) {
2541                                 verbosestream<<"InventoryMenu: The selected inventory list \""
2542                                                 <<s.listname<<"\" does not exist"<<std::endl;
2543                                 s.i = -1;  // make it invalid again
2544                                 break;
2545                         }
2546
2547                         if((u32)s.i >= list->getSize()) {
2548                                 infostream<<"InventoryMenu: The selected inventory list \""
2549                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
2550                                                 <<list->getSize()<<")"<<std::endl;
2551                                 s.i = -1;  // make it invalid again
2552                                 break;
2553                         }
2554
2555                         s_count = list->getItem(s.i).count;
2556                 } while(0);
2557
2558                 bool identical = (m_selected_item != NULL) && s.isValid() &&
2559                         (inv_selected == inv_s) &&
2560                         (m_selected_item->listname == s.listname) &&
2561                         (m_selected_item->i == s.i);
2562
2563                 // buttons: 0 = left, 1 = right, 2 = middle
2564                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event
2565                 int button = 0;
2566                 int updown = 2;
2567                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
2568                         { button = 0; updown = 0; }
2569                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
2570                         { button = 1; updown = 0; }
2571                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
2572                         { button = 2; updown = 0; }
2573                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
2574                         { button = 0; updown = 1; }
2575                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
2576                         { button = 1; updown = 1; }
2577                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
2578                         { button = 2; updown = 1; }
2579
2580                 // Set this number to a positive value to generate a move action
2581                 // from m_selected_item to s.
2582                 u32 move_amount = 0;
2583
2584                 // Set this number to a positive value to generate a drop action
2585                 // from m_selected_item.
2586                 u32 drop_amount = 0;
2587
2588                 // Set this number to a positive value to generate a craft action at s.
2589                 u32 craft_amount = 0;
2590
2591                 if(updown == 0) {
2592                         // Some mouse button has been pressed
2593
2594                         //infostream<<"Mouse button "<<button<<" pressed at p=("
2595                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2596
2597                         m_selected_dragging = false;
2598
2599                         if(s.isValid() && s.listname == "craftpreview") {
2600                                 // Craft preview has been clicked: craft
2601                                 craft_amount = (button == 2 ? 10 : 1);
2602                         }
2603                         else if(m_selected_item == NULL) {
2604                                 if(s_count != 0) {
2605                                         // Non-empty stack has been clicked: select it
2606                                         m_selected_item = new ItemSpec(s);
2607
2608                                         if(button == 1)  // right
2609                                                 m_selected_amount = (s_count + 1) / 2;
2610                                         else if(button == 2)  // middle
2611                                                 m_selected_amount = MYMIN(s_count, 10);
2612                                         else  // left
2613                                                 m_selected_amount = s_count;
2614
2615                                         m_selected_dragging = true;
2616                                 }
2617                         }
2618                         else { // m_selected_item != NULL
2619                                 assert(m_selected_amount >= 1);
2620
2621                                 if(s.isValid()) {
2622                                         // Clicked a slot: move
2623                                         if(button == 1)  // right
2624                                                 move_amount = 1;
2625                                         else if(button == 2)  // middle
2626                                                 move_amount = MYMIN(m_selected_amount, 10);
2627                                         else  // left
2628                                                 move_amount = m_selected_amount;
2629
2630                                         if(identical) {
2631                                                 if(move_amount >= m_selected_amount)
2632                                                         m_selected_amount = 0;
2633                                                 else
2634                                                         m_selected_amount -= move_amount;
2635                                                 move_amount = 0;
2636                                         }
2637                                 }
2638                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
2639                                         // Clicked outside of the window: drop
2640                                         if(button == 1)  // right
2641                                                 drop_amount = 1;
2642                                         else if(button == 2)  // middle
2643                                                 drop_amount = MYMIN(m_selected_amount, 10);
2644                                         else  // left
2645                                                 drop_amount = m_selected_amount;
2646                                 }
2647                         }
2648                 }
2649                 else if(updown == 1) {
2650                         // Some mouse button has been released
2651
2652                         //infostream<<"Mouse button "<<button<<" released at p=("
2653                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2654
2655                         if(m_selected_item != NULL && m_selected_dragging && s.isValid()) {
2656                                 if(!identical) {
2657                                         // Dragged to different slot: move all selected
2658                                         move_amount = m_selected_amount;
2659                                 }
2660                         }
2661                         else if(m_selected_item != NULL && m_selected_dragging &&
2662                                 !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
2663                                 // Dragged outside of window: drop all selected
2664                                 drop_amount = m_selected_amount;
2665                         }
2666
2667                         m_selected_dragging = false;
2668                 }
2669
2670                 // Possibly send inventory action to server
2671                 if(move_amount > 0)
2672                 {
2673                         // Send IACTION_MOVE
2674
2675                         assert(m_selected_item && m_selected_item->isValid());
2676                         assert(s.isValid());
2677
2678                         assert(inv_selected && inv_s);
2679                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2680                         InventoryList *list_to = inv_s->getList(s.listname);
2681                         assert(list_from && list_to);
2682                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2683                         ItemStack stack_to = list_to->getItem(s.i);
2684
2685                         // Check how many items can be moved
2686                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
2687                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
2688                         // If source stack cannot be added to destination stack at all,
2689                         // they are swapped
2690                         if ((leftover.count == stack_from.count) &&
2691                                         (leftover.name == stack_from.name)) {
2692                                 m_selected_amount = stack_to.count;
2693                                 // In case the server doesn't directly swap them but instead
2694                                 // moves stack_to somewhere else, set this
2695                                 m_selected_content_guess = stack_to;
2696                                 m_selected_content_guess_inventory = s.inventoryloc;
2697                         }
2698                         // Source stack goes fully into destination stack
2699                         else if(leftover.empty()) {
2700                                 m_selected_amount -= move_amount;
2701                                 m_selected_content_guess = ItemStack(); // Clear
2702                         }
2703                         // Source stack goes partly into destination stack
2704                         else {
2705                                 move_amount -= leftover.count;
2706                                 m_selected_amount -= move_amount;
2707                                 m_selected_content_guess = ItemStack(); // Clear
2708                         }
2709
2710                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
2711                         IMoveAction *a = new IMoveAction();
2712                         a->count = move_amount;
2713                         a->from_inv = m_selected_item->inventoryloc;
2714                         a->from_list = m_selected_item->listname;
2715                         a->from_i = m_selected_item->i;
2716                         a->to_inv = s.inventoryloc;
2717                         a->to_list = s.listname;
2718                         a->to_i = s.i;
2719                         m_invmgr->inventoryAction(a);
2720                 }
2721                 else if(drop_amount > 0) {
2722                         m_selected_content_guess = ItemStack(); // Clear
2723
2724                         // Send IACTION_DROP
2725
2726                         assert(m_selected_item && m_selected_item->isValid());
2727                         assert(inv_selected);
2728                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2729                         assert(list_from);
2730                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2731
2732                         // Check how many items can be dropped
2733                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
2734                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
2735                         m_selected_amount -= drop_amount;
2736
2737                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
2738                         IDropAction *a = new IDropAction();
2739                         a->count = drop_amount;
2740                         a->from_inv = m_selected_item->inventoryloc;
2741                         a->from_list = m_selected_item->listname;
2742                         a->from_i = m_selected_item->i;
2743                         m_invmgr->inventoryAction(a);
2744                 }
2745                 else if(craft_amount > 0) {
2746                         m_selected_content_guess = ItemStack(); // Clear
2747
2748                         // Send IACTION_CRAFT
2749
2750                         assert(s.isValid());
2751                         assert(inv_s);
2752
2753                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
2754                         ICraftAction *a = new ICraftAction();
2755                         a->count = craft_amount;
2756                         a->craft_inv = s.inventoryloc;
2757                         m_invmgr->inventoryAction(a);
2758                 }
2759
2760                 // If m_selected_amount has been decreased to zero, deselect
2761                 if(m_selected_amount == 0) {
2762                         delete m_selected_item;
2763                         m_selected_item = NULL;
2764                         m_selected_amount = 0;
2765                         m_selected_dragging = false;
2766                         m_selected_content_guess = ItemStack();
2767                 }
2768         }
2769         if(event.EventType==EET_GUI_EVENT) {
2770
2771                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
2772                                 && isVisible()) {
2773                         // find the element that was clicked
2774                         for(unsigned int i=0; i<m_fields.size(); i++) {
2775                                 FieldSpec &s = m_fields[i];
2776                                 if ((s.ftype == f_TabHeader) &&
2777                                                 (s.fid == event.GUIEvent.Caller->getID())) {
2778                                         s.send = true;
2779                                         acceptInput();
2780                                         s.send = false;
2781                                         return true;
2782                                 }
2783                         }
2784                 }
2785                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
2786                                 && isVisible()) {
2787                         if(!canTakeFocus(event.GUIEvent.Element)) {
2788                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
2789                                                 <<std::endl;
2790                                 // Returning true disables focus change
2791                                 return true;
2792                         }
2793                 }
2794                 if((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
2795                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
2796                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED)) {
2797                         unsigned int btn_id = event.GUIEvent.Caller->getID();
2798
2799                         if (btn_id == 257) {
2800                                 if (m_allowclose) {
2801                                         acceptInput(quit_mode_accept);
2802                                         quitMenu();
2803                                 } else {
2804                                         acceptInput();
2805                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2806                                 }
2807                                 // quitMenu deallocates menu
2808                                 return true;
2809                         }
2810
2811                         // find the element that was clicked
2812                         for(u32 i=0; i<m_fields.size(); i++) {
2813                                 FieldSpec &s = m_fields[i];
2814                                 // if its a button, set the send field so
2815                                 // lua knows which button was pressed
2816                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
2817                                                 (s.fid == event.GUIEvent.Caller->getID())) {
2818                                         s.send = true;
2819                                         if(s.is_exit) {
2820                                                 if (m_allowclose) {
2821                                                         acceptInput(quit_mode_accept);
2822                                                         quitMenu();
2823                                                 } else {
2824                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2825                                                 }
2826                                                 return true;
2827                                         } else {
2828                                                 acceptInput(quit_mode_no);
2829                                                 s.send = false;
2830                                                 return true;
2831                                         }
2832                                 }
2833                                 if ((s.ftype == f_DropDown) &&
2834                                                 (s.fid == event.GUIEvent.Caller->getID())) {
2835                                         // only send the changed dropdown
2836                                         for(u32 i=0; i<m_fields.size(); i++) {
2837                                                 FieldSpec &s2 = m_fields[i];
2838                                                 if (s2.ftype == f_DropDown) {
2839                                                         s2.send = false;
2840                                                 }
2841                                         }
2842                                         s.send = true;
2843                                         acceptInput(quit_mode_no);
2844
2845                                         // revert configuration to make sure dropdowns are sent on
2846                                         // regular button click
2847                                         for(u32 i=0; i<m_fields.size(); i++) {
2848                                                 FieldSpec &s2 = m_fields[i];
2849                                                 if (s2.ftype == f_DropDown) {
2850                                                         s2.send = true;
2851                                                 }
2852                                         }
2853                                         return true;
2854                                 }
2855                         }
2856                 }
2857                 if(event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
2858                         if(event.GUIEvent.Caller->getID() > 257) {
2859
2860                                 if (m_allowclose) {
2861                                         acceptInput(quit_mode_accept);
2862                                         quitMenu();
2863                                 } else {
2864                                         current_keys_pending.key_enter = true;
2865                                         acceptInput();
2866                                 }
2867                                 // quitMenu deallocates menu
2868                                 return true;
2869                         }
2870                 }
2871
2872                 if(event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
2873                         int current_id = event.GUIEvent.Caller->getID();
2874                         if(current_id > 257) {
2875                                 // find the element that was clicked
2876                                 for(u32 i=0; i<m_fields.size(); i++) {
2877                                         FieldSpec &s = m_fields[i];
2878                                         // if it's a table, set the send field
2879                                         // so lua knows which table was changed
2880                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
2881                                                 s.send = true;
2882                                                 acceptInput();
2883                                                 s.send=false;
2884                                         }
2885                                 }
2886                                 return true;
2887                         }
2888                 }
2889         }
2890
2891         return Parent ? Parent->OnEvent(event) : false;
2892 }
2893
2894 bool GUIFormSpecMenu::parseColor(const std::string &value, video::SColor &color,
2895                 bool quiet)
2896 {
2897         const char *hexpattern = NULL;
2898         if (value[0] == '#') {
2899                 if (value.size() == 9)
2900                         hexpattern = "#RRGGBBAA";
2901                 else if (value.size() == 7)
2902                         hexpattern = "#RRGGBB";
2903                 else if (value.size() == 5)
2904                         hexpattern = "#RGBA";
2905                 else if (value.size() == 4)
2906                         hexpattern = "#RGB";
2907         }
2908
2909         if (hexpattern) {
2910                 assert(strlen(hexpattern) == value.size());
2911                 video::SColor outcolor(255, 255, 255, 255);
2912                 for (size_t pos = 0; pos < value.size(); ++pos) {
2913                         // '#' in the pattern means skip that character
2914                         if (hexpattern[pos] == '#')
2915                                 continue;
2916
2917                         // Else assume hexpattern[pos] is one of 'R' 'G' 'B' 'A'
2918                         // Read one or two digits, depending on hexpattern
2919                         unsigned char c1, c2;
2920                         if (hexpattern[pos+1] == hexpattern[pos]) {
2921                                 // Two digits, e.g. hexpattern == "#RRGGBB"
2922                                 if (!hex_digit_decode(value[pos], c1) ||
2923                                     !hex_digit_decode(value[pos+1], c2))
2924                                         goto fail;
2925                                 ++pos;
2926                         }
2927                         else {
2928                                 // One digit, e.g. hexpattern == "#RGB"
2929                                 if (!hex_digit_decode(value[pos], c1))
2930                                         goto fail;
2931                                 c2 = c1;
2932                         }
2933                         u32 colorpart = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
2934
2935                         // Update outcolor with newly read color part
2936                         if (hexpattern[pos] == 'R')
2937                                 outcolor.setRed(colorpart);
2938                         else if (hexpattern[pos] == 'G')
2939                                 outcolor.setGreen(colorpart);
2940                         else if (hexpattern[pos] == 'B')
2941                                 outcolor.setBlue(colorpart);
2942                         else if (hexpattern[pos] == 'A')
2943                                 outcolor.setAlpha(colorpart);
2944                 }
2945
2946                 color = outcolor;
2947                 return true;
2948         }
2949
2950         // Optionally, named colors could be implemented here
2951
2952 fail:
2953         if (!quiet)
2954                 errorstream<<"Invalid color: \""<<value<<"\""<<std::endl;
2955         return false;
2956 }