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