3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
26 #include "guiFormSpecMenu.h"
27 #include "guiScrollBar.h"
29 #include "constants.h"
31 #include "client/keycode.h"
32 #include "util/strfnd.h"
33 #include <IGUIButton.h>
34 #include <IGUICheckBox.h>
35 #include <IGUIComboBox.h>
36 #include <IGUIEditBox.h>
37 #include <IGUIStaticText.h>
39 #include <IGUITabControl.h>
40 #include "client/renderingengine.h"
42 #include "client/tile.h" // ITextureSource
43 #include "client/hud.h" // drawItemStack
47 #include "scripting_server.h"
48 #include "mainmenumanager.h"
51 #include "client/client.h"
52 #include "client/fontengine.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "guiBackgroundImage.h"
60 #include "guiButton.h"
61 #include "guiButtonImage.h"
62 #include "guiButtonItemImage.h"
63 #include "guiEditBoxWithScrollbar.h"
64 #include "guiItemImage.h"
65 #include "guiScrollBar.h"
67 #include "intlGUIEditBox.h"
68 #include "guiHyperText.h"
70 #define MY_CHECKPOS(a,b) \
71 if (v_pos.size() != 2) { \
72 errorstream<< "Invalid pos for element " << a << "specified: \"" \
73 << parts[b] << "\"" << std::endl; \
77 #define MY_CHECKGEOM(a,b) \
78 if (v_geom.size() != 2) { \
79 errorstream<< "Invalid geometry for element " << a << \
80 "specified: \"" << parts[b] << "\"" << std::endl; \
86 static unsigned int font_line_height(gui::IGUIFont *font)
88 return font->getDimension(L"Ay").Height + font->getKerningHeight();
91 inline u32 clamp_u8(s32 value)
93 return (u32) MYMIN(MYMAX(value, 0), 255);
96 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
97 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
98 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
99 const std::string &formspecPrepend,
100 bool remap_dbl_click):
101 GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
105 m_formspec_prepend(formspecPrepend),
108 m_joystick(joystick),
109 m_remap_dbl_click(remap_dbl_click)
111 current_keys_pending.key_down = false;
112 current_keys_pending.key_up = false;
113 current_keys_pending.key_enter = false;
114 current_keys_pending.key_escape = false;
116 m_doubleclickdetect[0].time = 0;
117 m_doubleclickdetect[1].time = 0;
119 m_doubleclickdetect[0].pos = v2s32(0, 0);
120 m_doubleclickdetect[1].pos = v2s32(0, 0);
122 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
123 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
126 GUIFormSpecMenu::~GUIFormSpecMenu()
130 for (auto &table_it : m_tables)
131 table_it.second->drop();
132 for (auto &inventorylist_it : m_inventorylists)
133 inventorylist_it.e->drop();
134 for (auto &checkbox_it : m_checkboxes)
135 checkbox_it.second->drop();
136 for (auto &scrollbar_it : m_scrollbars)
137 scrollbar_it.second->drop();
138 for (auto &background_it : m_backgrounds)
139 background_it->drop();
140 for (auto &tooltip_rect_it : m_tooltip_rects)
141 tooltip_rect_it.first->drop();
143 delete m_selected_item;
148 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
149 JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
150 const std::string &formspecPrepend)
152 if (cur_formspec == nullptr) {
153 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
154 client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
155 cur_formspec->doPause = false;
158 Caution: do not call (*cur_formspec)->drop() here --
159 the reference might outlive the menu, so we will
160 periodically check if *cur_formspec is the only
161 remaining reference (i.e. the menu was removed)
162 and delete it in that case.
166 cur_formspec->setFormspecPrepend(formspecPrepend);
167 cur_formspec->setFormSource(fs_src);
168 cur_formspec->setTextDest(txt_dest);
172 void GUIFormSpecMenu::removeChildren()
174 const core::list<gui::IGUIElement*> &children = getChildren();
176 while (!children.empty()) {
177 (*children.getLast())->remove();
180 if (m_tooltip_element) {
181 m_tooltip_element->remove();
182 m_tooltip_element->drop();
183 m_tooltip_element = nullptr;
187 void GUIFormSpecMenu::setInitialFocus()
189 // Set initial focus according to following order of precedence:
190 // 1. first empty editbox
194 // 5. first focusable (not statictext, not tabheader)
195 // 6. first child element
197 core::list<gui::IGUIElement*> children = getChildren();
199 // in case "children" contains any NULL elements, remove them
200 for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
201 it != children.end();) {
205 it = children.erase(it);
208 // 1. first empty editbox
209 for (gui::IGUIElement *it : children) {
210 if (it->getType() == gui::EGUIET_EDIT_BOX
211 && it->getText()[0] == 0) {
212 Environment->setFocus(it);
218 for (gui::IGUIElement *it : children) {
219 if (it->getType() == gui::EGUIET_EDIT_BOX) {
220 Environment->setFocus(it);
226 for (gui::IGUIElement *it : children) {
227 if (it->getTypeName() == std::string("GUITable")) {
228 Environment->setFocus(it);
234 for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
235 it != children.end(); --it) {
236 if ((*it)->getType() == gui::EGUIET_BUTTON) {
237 Environment->setFocus(*it);
242 // 5. first focusable (not statictext, not tabheader)
243 for (gui::IGUIElement *it : children) {
244 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
245 it->getType() != gui::EGUIET_TAB_CONTROL) {
246 Environment->setFocus(it);
251 // 6. first child element
252 if (children.empty())
253 Environment->setFocus(this);
255 Environment->setFocus(*(children.begin()));
258 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
260 for (auto &table : m_tables) {
261 if (tablename == table.first.fname)
267 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
269 for (auto &dropdown : m_dropdowns) {
270 if (name == dropdown.first.fname)
271 return &dropdown.second;
276 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
278 v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
280 pos_f.X += stof((*v_pos)[0]) * spacing.X;
281 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
283 return v2s32(pos_f.X, pos_f.Y);
286 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
288 return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
289 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
292 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
294 return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
297 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
299 std::vector<std::string> parts = split(element,',');
301 if (((parts.size() == 2) || parts.size() == 3) ||
302 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
304 if (parts[1].find(';') != std::string::npos)
305 parts[1] = parts[1].substr(0,parts[1].find(';'));
307 data->invsize.X = MYMAX(0, stof(parts[0]));
308 data->invsize.Y = MYMAX(0, stof(parts[1]));
312 if (parts.size() == 3) {
313 if (parts[2] == "true") {
314 lockSize(true,v2u32(800,600));
318 data->explicit_size = true;
321 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
324 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
326 std::vector<std::string> parts = split(element, ',');
328 if (parts.size() >= 2) {
329 if (parts[1].find(';') != std::string::npos)
330 parts[1] = parts[1].substr(0, parts[1].find(';'));
332 container_stack.push(pos_offset);
333 pos_offset.X += stof(parts[0]);
334 pos_offset.Y += stof(parts[1]);
337 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
340 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
342 if (container_stack.empty()) {
343 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
345 pos_offset = container_stack.top();
346 container_stack.pop();
350 void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
353 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
357 std::vector<std::string> parts = split(element,';');
359 if (((parts.size() == 4) || (parts.size() == 5)) ||
360 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
362 std::string location = parts[0];
363 std::string listname = parts[1];
364 std::vector<std::string> v_pos = split(parts[2],',');
365 std::vector<std::string> v_geom = split(parts[3],',');
366 std::string startindex;
367 if (parts.size() == 5)
368 startindex = parts[4];
370 MY_CHECKPOS("list",2);
371 MY_CHECKGEOM("list",3);
373 InventoryLocation loc;
375 if (location == "context" || location == "current_name")
376 loc = m_current_inventory_location;
378 loc.deSerialize(location);
381 geom.X = stoi(v_geom[0]);
382 geom.Y = stoi(v_geom[1]);
385 if (!startindex.empty())
386 start_i = stoi(startindex);
388 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
389 errorstream<< "Invalid list element: '" << element << "'" << std::endl;
393 // check for the existence of inventory and list
394 Inventory *inv = m_invmgr->getInventory(loc);
396 warningstream << "GUIFormSpecMenu::parseList(): "
397 << "The inventory location "
398 << "\"" << loc.dump() << "\" doesn't exist"
402 InventoryList *ilist = inv->getList(listname);
404 warningstream << "GUIFormSpecMenu::parseList(): "
405 << "The inventory list \"" << listname << "\" "
406 << "@ \"" << loc.dump() << "\" doesn't exist"
411 // trim geom if it is larger than the actual inventory size
412 s32 list_size = (s32)ilist->getSize();
413 if (list_size < geom.X * geom.Y + start_i) {
414 list_size -= MYMAX(start_i, 0);
415 geom.Y = list_size / geom.X;
416 geom.Y += list_size % geom.X > 0 ? 1 : 0;
421 if (!data->explicit_size)
422 warningstream << "invalid use of list without a size[] element" << std::endl;
428 258 + m_fields.size(),
433 core::rect<s32> rect;
435 if (data->real_coordinates) {
436 pos = getRealCoordinateBasePos(v_pos);
437 rect = core::rect<s32>(pos.X, pos.Y,
438 pos.X + (geom.X - 1) * (imgsize.X * 1.25) + imgsize.X,
439 pos.Y + (geom.Y - 1) * (imgsize.Y * 1.25) + imgsize.Y);
441 pos = getElementBasePos(&v_pos);
442 rect = core::rect<s32>(pos.X, pos.Y,
443 pos.X + (geom.X - 1) * spacing.X + imgsize.X,
444 pos.Y + (geom.Y - 1) * spacing.Y + imgsize.Y);
447 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
448 this, spec.fid, rect);
450 // the element the list is bound to should not block mouse-clicks
451 e->setVisible(false);
453 m_inventorylists.emplace_back(loc, listname, e, geom, start_i,
454 data->real_coordinates);
455 m_fields.push_back(spec);
458 errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl;
461 void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element)
464 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
468 std::vector<std::string> parts = split(element, ';');
470 if (parts.size() == 2) {
471 std::string location = parts[0];
472 std::string listname = parts[1];
474 InventoryLocation loc;
476 if (location == "context" || location == "current_name")
477 loc = m_current_inventory_location;
479 loc.deSerialize(location);
481 m_inventory_rings.emplace_back(loc, listname);
485 if (element.empty() && m_inventorylists.size() > 1) {
486 size_t siz = m_inventorylists.size();
487 // insert the last two inv list elements into the list ring
488 const ListDrawSpec &spa = m_inventorylists[siz - 2];
489 const ListDrawSpec &spb = m_inventorylists[siz - 1];
490 m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname);
491 m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname);
495 errorstream<< "Invalid list ring element(" << parts.size() << ", "
496 << m_inventorylists.size() << "): '" << element << "'" << std::endl;
499 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
501 std::vector<std::string> parts = split(element,';');
503 if (((parts.size() >= 3) && (parts.size() <= 4)) ||
504 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
506 std::vector<std::string> v_pos = split(parts[0],',');
507 std::string name = parts[1];
508 std::string label = parts[2];
509 std::string selected;
511 if (parts.size() >= 4)
514 MY_CHECKPOS("checkbox",0);
516 bool fselected = false;
518 if (selected == "true")
521 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
522 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
523 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
524 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
527 core::rect<s32> rect;
529 if (data->real_coordinates) {
530 pos = getRealCoordinateBasePos(v_pos);
532 rect = core::rect<s32>(
535 pos.X + label_size.Width + cb_size + 7,
539 pos = getElementBasePos(&v_pos);
540 rect = core::rect<s32>(
542 pos.Y + imgsize.Y / 2 - y_center,
543 pos.X + label_size.Width + cb_size + 7,
544 pos.Y + imgsize.Y / 2 + y_center
550 wlabel, //Needed for displaying text on MSVC
555 spec.ftype = f_CheckBox;
557 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect, this,
558 spec.fid, spec.flabel.c_str());
560 auto style = getStyleForElement("checkbox", name);
561 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
563 if (spec.fname == data->focused_fieldname) {
564 Environment->setFocus(e);
568 m_checkboxes.emplace_back(spec, e);
569 m_fields.push_back(spec);
572 errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl;
575 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
577 std::vector<std::string> parts = split(element,';');
579 if (parts.size() >= 5) {
580 std::vector<std::string> v_pos = split(parts[0],',');
581 std::vector<std::string> v_geom = split(parts[1],',');
582 std::string name = parts[3];
583 std::string value = parts[4];
585 MY_CHECKPOS("scrollbar",0);
586 MY_CHECKGEOM("scrollbar",1);
591 if (data->real_coordinates) {
592 pos = getRealCoordinateBasePos(v_pos);
593 dim = getRealCoordinateGeometry(v_geom);
595 pos = getElementBasePos(&v_pos);
596 dim.X = stof(v_geom[0]) * spacing.X;
597 dim.Y = stof(v_geom[1]) * spacing.Y;
600 core::rect<s32> rect =
601 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
610 bool is_horizontal = true;
612 if (parts[2] == "vertical")
613 is_horizontal = false;
615 spec.ftype = f_ScrollBar;
617 GUIScrollBar *e = new GUIScrollBar(Environment, this, spec.fid, rect,
618 is_horizontal, true);
620 auto style = getStyleForElement("scrollbar", name);
621 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
622 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
624 s32 max = data->scrollbar_options.max;
625 s32 min = data->scrollbar_options.min;
630 e->setPos(stoi(parts[4]));
632 e->setSmallStep(data->scrollbar_options.small_step);
633 e->setLargeStep(data->scrollbar_options.large_step);
635 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
637 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
639 m_scrollbars.emplace_back(spec,e);
640 m_fields.push_back(spec);
643 errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element
647 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
649 std::vector<std::string> parts = split(element, ';');
651 if (parts.size() == 0) {
652 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
653 element << "'" << std::endl;
657 for (const std::string &i : parts) {
658 std::vector<std::string> options = split(i, '=');
660 if (options.size() != 2) {
661 warningstream << "Invalid scrollbaroptions option syntax: '" <<
662 element << "'" << std::endl;
663 continue; // Go to next option
666 if (options[0] == "max") {
667 data->scrollbar_options.max = stoi(options[1]);
669 } else if (options[0] == "min") {
670 data->scrollbar_options.min = stoi(options[1]);
672 } else if (options[0] == "smallstep") {
673 int value = stoi(options[1]);
674 data->scrollbar_options.small_step = value < 0 ? 10 : value;
676 } else if (options[0] == "largestep") {
677 int value = stoi(options[1]);
678 data->scrollbar_options.large_step = value < 0 ? 100 : value;
680 } else if (options[0] == "thumbsize") {
681 int value = stoi(options[1]);
682 data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
684 } else if (options[0] == "arrows") {
685 std::string value = trim(options[1]);
687 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
688 else if (value == "show")
689 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
690 else // Auto hide/show
691 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
695 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
696 "): '" << element << "'" << std::endl;
700 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
702 std::vector<std::string> parts = split(element,';');
704 if ((parts.size() == 3) ||
705 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
707 std::vector<std::string> v_pos = split(parts[0],',');
708 std::vector<std::string> v_geom = split(parts[1],',');
709 std::string name = unescape_string(parts[2]);
711 MY_CHECKPOS("image", 0);
712 MY_CHECKGEOM("image", 1);
717 if (data->real_coordinates) {
718 pos = getRealCoordinateBasePos(v_pos);
719 geom = getRealCoordinateGeometry(v_geom);
721 pos = getElementBasePos(&v_pos);
722 geom.X = stof(v_geom[0]) * (float)imgsize.X;
723 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
726 if (!data->explicit_size)
727 warningstream<<"invalid use of image without a size[] element"<<std::endl;
729 video::ITexture *texture = m_tsrc->getTexture(name);
731 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
732 << std::endl << "\t" << name << std::endl;
740 258 + m_fields.size(),
743 core::rect<s32> rect(pos, pos + geom);
744 gui::IGUIImage *e = Environment->addImage(rect, this, spec.fid, 0, true);
745 e->setImage(texture);
746 e->setScaleImage(true);
747 e->setNotClipped(true);
748 m_fields.push_back(spec);
753 if (parts.size() == 2) {
754 std::vector<std::string> v_pos = split(parts[0],',');
755 std::string name = unescape_string(parts[1]);
757 MY_CHECKPOS("image", 0);
759 v2s32 pos = getElementBasePos(&v_pos);
761 if (!data->explicit_size)
762 warningstream<<"invalid use of image without a size[] element"<<std::endl;
764 video::ITexture *texture = m_tsrc->getTexture(name);
766 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
767 << std::endl << "\t" << name << std::endl;
775 258 + m_fields.size()
777 gui::IGUIImage *e = Environment->addImage(texture, pos, true, this,
779 e->setNotClipped(true);
780 m_fields.push_back(spec);
784 errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl;
787 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
789 std::vector<std::string> parts = split(element,';');
791 if ((parts.size() == 3) ||
792 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
794 std::vector<std::string> v_pos = split(parts[0],',');
795 std::vector<std::string> v_geom = split(parts[1],',');
796 std::string name = parts[2];
798 MY_CHECKPOS("itemimage",0);
799 MY_CHECKGEOM("itemimage",1);
804 if (data->real_coordinates) {
805 pos = getRealCoordinateBasePos(v_pos);
806 geom = getRealCoordinateGeometry(v_geom);
808 pos = getElementBasePos(&v_pos);
809 geom.X = stof(v_geom[0]) * (float)imgsize.X;
810 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
813 if(!data->explicit_size)
814 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
820 258 + m_fields.size(),
823 spec.ftype = f_ItemImage;
825 GUIItemImage *e = new GUIItemImage(Environment, this, spec.fid,
826 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
829 m_fields.push_back(spec);
832 errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
835 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
836 const std::string &type)
838 std::vector<std::string> parts = split(element,';');
840 if ((parts.size() == 4) ||
841 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
843 std::vector<std::string> v_pos = split(parts[0],',');
844 std::vector<std::string> v_geom = split(parts[1],',');
845 std::string name = parts[2];
846 std::string label = parts[3];
848 MY_CHECKPOS("button",0);
849 MY_CHECKGEOM("button",1);
853 core::rect<s32> rect;
855 if (data->real_coordinates) {
856 pos = getRealCoordinateBasePos(v_pos);
857 geom = getRealCoordinateGeometry(v_geom);
858 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
861 pos = getElementBasePos(&v_pos);
862 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
863 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
865 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
866 pos.X + geom.X, pos.Y + m_btn_height);
869 if(!data->explicit_size)
870 warningstream<<"invalid use of button without a size[] element"<<std::endl;
872 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
878 258 + m_fields.size()
880 spec.ftype = f_Button;
881 if(type == "button_exit")
884 GUIButton *e = GUIButton::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
886 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
887 e->setFromStyle(style, m_tsrc);
889 if (spec.fname == data->focused_fieldname) {
890 Environment->setFocus(e);
893 m_fields.push_back(spec);
896 errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl;
899 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
901 std::vector<std::string> parts = split(element,';');
903 if ((parts.size() >= 3 && parts.size() <= 5) ||
904 (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
905 std::vector<std::string> v_pos = split(parts[0],',');
906 std::vector<std::string> v_geom = split(parts[1],',');
907 std::string name = unescape_string(parts[2]);
909 MY_CHECKPOS("background",0);
910 MY_CHECKGEOM("background",1);
915 if (data->real_coordinates) {
916 pos = getRealCoordinateBasePos(v_pos);
917 geom = getRealCoordinateGeometry(v_geom);
919 pos = getElementBasePos(&v_pos);
920 pos.X -= (spacing.X - (float)imgsize.X) / 2;
921 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
923 geom.X = stof(v_geom[0]) * spacing.X;
924 geom.Y = stof(v_geom[1]) * spacing.Y;
928 if (parts.size() >= 4 && is_yes(parts[3])) {
929 if (data->real_coordinates) {
930 pos = getRealCoordinateBasePos(v_pos) * -1;
933 pos.X = stoi(v_pos[0]); //acts as offset
934 pos.Y = stoi(v_pos[1]);
939 core::rect<s32> middle;
940 if (parts.size() >= 5) {
941 std::vector<std::string> v_middle = split(parts[4], ',');
942 if (v_middle.size() == 1) {
943 s32 x = stoi(v_middle[0]);
944 middle.UpperLeftCorner = core::vector2di(x, x);
945 middle.LowerRightCorner = core::vector2di(-x, -x);
946 } else if (v_middle.size() == 2) {
947 s32 x = stoi(v_middle[0]);
948 s32 y = stoi(v_middle[1]);
949 middle.UpperLeftCorner = core::vector2di(x, y);
950 middle.LowerRightCorner = core::vector2di(-x, -y);
951 // `-x` is interpreted as `w - x`
952 } else if (v_middle.size() == 4) {
953 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
954 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
956 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
960 if (!data->explicit_size && !clip)
961 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
967 258 + m_fields.size()
970 core::rect<s32> rect;
972 // no auto_clip => position like normal image
973 rect = core::rect<s32>(pos, pos + geom);
975 // it will be auto-clipped when drawing
976 rect = core::rect<s32>(-pos, pos);
979 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
980 rect, name, middle, m_tsrc, clip);
982 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
984 e->setNotClipped(true);
986 e->setVisible(false); // the element is drawn manually before all others
988 m_backgrounds.push_back(e);
989 m_fields.push_back(spec);
992 errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl;
995 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
997 std::vector<std::string> parts = split(element,';');
999 data->table_options.clear();
1000 for (const std::string &part : parts) {
1001 // Parse table option
1002 std::string opt = unescape_string(part);
1003 data->table_options.push_back(GUITable::splitOption(opt));
1007 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1009 std::vector<std::string> parts = split(element,';');
1011 data->table_columns.clear();
1012 for (const std::string &part : parts) {
1013 std::vector<std::string> col_parts = split(part,',');
1014 GUITable::TableColumn column;
1015 // Parse column type
1016 if (!col_parts.empty())
1017 column.type = col_parts[0];
1018 // Parse column options
1019 for (size_t j = 1; j < col_parts.size(); ++j) {
1020 std::string opt = unescape_string(col_parts[j]);
1021 column.options.push_back(GUITable::splitOption(opt));
1023 data->table_columns.push_back(column);
1027 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1029 std::vector<std::string> parts = split(element,';');
1031 if (((parts.size() == 4) || (parts.size() == 5)) ||
1032 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1034 std::vector<std::string> v_pos = split(parts[0],',');
1035 std::vector<std::string> v_geom = split(parts[1],',');
1036 std::string name = parts[2];
1037 std::vector<std::string> items = split(parts[3],',');
1038 std::string str_initial_selection;
1039 std::string str_transparent = "false";
1041 if (parts.size() >= 5)
1042 str_initial_selection = parts[4];
1044 MY_CHECKPOS("table",0);
1045 MY_CHECKGEOM("table",1);
1050 if (data->real_coordinates) {
1051 pos = getRealCoordinateBasePos(v_pos);
1052 geom = getRealCoordinateGeometry(v_geom);
1054 pos = getElementBasePos(&v_pos);
1055 geom.X = stof(v_geom[0]) * spacing.X;
1056 geom.Y = stof(v_geom[1]) * spacing.Y;
1059 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1065 258 + m_fields.size()
1068 spec.ftype = f_Table;
1070 for (std::string &item : items) {
1071 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1074 //now really show table
1075 GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc);
1077 if (spec.fname == data->focused_fieldname) {
1078 Environment->setFocus(e);
1081 e->setTable(data->table_options, data->table_columns, items);
1083 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1084 e->setDynamicData(data->table_dyndata[name]);
1087 if (!str_initial_selection.empty() && str_initial_selection != "0")
1088 e->setSelected(stoi(str_initial_selection));
1090 auto style = getStyleForElement("table", name);
1091 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1093 m_tables.emplace_back(spec, e);
1094 m_fields.push_back(spec);
1097 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1100 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1102 std::vector<std::string> parts = split(element,';');
1104 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1105 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1107 std::vector<std::string> v_pos = split(parts[0],',');
1108 std::vector<std::string> v_geom = split(parts[1],',');
1109 std::string name = parts[2];
1110 std::vector<std::string> items = split(parts[3],',');
1111 std::string str_initial_selection;
1112 std::string str_transparent = "false";
1114 if (parts.size() >= 5)
1115 str_initial_selection = parts[4];
1117 if (parts.size() >= 6)
1118 str_transparent = parts[5];
1120 MY_CHECKPOS("textlist",0);
1121 MY_CHECKGEOM("textlist",1);
1126 if (data->real_coordinates) {
1127 pos = getRealCoordinateBasePos(v_pos);
1128 geom = getRealCoordinateGeometry(v_geom);
1130 pos = getElementBasePos(&v_pos);
1131 geom.X = stof(v_geom[0]) * spacing.X;
1132 geom.Y = stof(v_geom[1]) * spacing.Y;
1135 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1141 258 + m_fields.size()
1144 spec.ftype = f_Table;
1146 for (std::string &item : items) {
1147 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1150 //now really show list
1151 GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc);
1153 if (spec.fname == data->focused_fieldname) {
1154 Environment->setFocus(e);
1157 e->setTextList(items, is_yes(str_transparent));
1159 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1160 e->setDynamicData(data->table_dyndata[name]);
1163 if (!str_initial_selection.empty() && str_initial_selection != "0")
1164 e->setSelected(stoi(str_initial_selection));
1166 auto style = getStyleForElement("textlist", name);
1167 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1169 m_tables.emplace_back(spec, e);
1170 m_fields.push_back(spec);
1173 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1177 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1179 std::vector<std::string> parts = split(element,';');
1181 if ((parts.size() == 5) ||
1182 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1184 std::vector<std::string> v_pos = split(parts[0],',');
1185 std::string name = parts[2];
1186 std::vector<std::string> items = split(parts[3],',');
1187 std::string str_initial_selection;
1188 str_initial_selection = parts[4];
1190 MY_CHECKPOS("dropdown",0);
1194 core::rect<s32> rect;
1196 if (data->real_coordinates) {
1197 std::vector<std::string> v_geom = split(parts[1],',');
1199 if (v_geom.size() == 1)
1200 v_geom.emplace_back("1");
1202 MY_CHECKGEOM("dropdown",1);
1204 pos = getRealCoordinateBasePos(v_pos);
1205 geom = getRealCoordinateGeometry(v_geom);
1206 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1208 pos = getElementBasePos(&v_pos);
1210 s32 width = stof(parts[1]) * spacing.Y;
1212 rect = core::rect<s32>(pos.X, pos.Y,
1213 pos.X + width, pos.Y + (m_btn_height * 2));
1220 258 + m_fields.size()
1223 spec.ftype = f_DropDown;
1226 //now really show list
1227 gui::IGUIComboBox *e = Environment->addComboBox(rect, this, spec.fid);
1229 if (spec.fname == data->focused_fieldname) {
1230 Environment->setFocus(e);
1233 for (const std::string &item : items) {
1234 e->addItem(unescape_translate(unescape_string(
1235 utf8_to_wide(item))).c_str());
1238 if (!str_initial_selection.empty())
1239 e->setSelected(stoi(str_initial_selection)-1);
1241 auto style = getStyleForElement("dropdown", name);
1242 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1244 m_fields.push_back(spec);
1246 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1247 std::vector<std::string> &values = m_dropdowns.back().second;
1248 for (const std::string &item : items) {
1249 values.push_back(unescape_string(item));
1254 errorstream << "Invalid dropdown element(" << parts.size() << "): '"
1255 << element << "'" << std::endl;
1258 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1260 std::vector<std::string> parts = split(element,';');
1261 if (parts.size() == 2 ||
1262 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1263 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1267 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1269 std::vector<std::string> parts = split(element,';');
1271 if ((parts.size() == 4) || (parts.size() == 5) ||
1272 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1274 std::vector<std::string> v_pos = split(parts[0],',');
1275 std::vector<std::string> v_geom = split(parts[1],',');
1276 std::string name = parts[2];
1277 std::string label = parts[3];
1279 MY_CHECKPOS("pwdfield",0);
1280 MY_CHECKGEOM("pwdfield",1);
1285 if (data->real_coordinates) {
1286 pos = getRealCoordinateBasePos(v_pos);
1287 geom = getRealCoordinateGeometry(v_geom);
1289 pos = getElementBasePos(&v_pos);
1292 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1294 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1295 pos.Y -= m_btn_height;
1296 geom.Y = m_btn_height*2;
1299 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1301 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1307 258 + m_fields.size()
1311 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
1313 if (spec.fname == data->focused_fieldname) {
1314 Environment->setFocus(e);
1317 if (label.length() >= 1) {
1318 int font_height = g_fontengine->getTextHeight();
1319 rect.UpperLeftCorner.Y -= font_height;
1320 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1321 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1325 e->setPasswordBox(true,L'*');
1327 auto style = getStyleForElement("pwdfield", name, "field");
1328 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1329 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1330 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1333 evt.EventType = EET_KEY_INPUT_EVENT;
1334 evt.KeyInput.Key = KEY_END;
1335 evt.KeyInput.Char = 0;
1336 evt.KeyInput.Control = false;
1337 evt.KeyInput.Shift = false;
1338 evt.KeyInput.PressedDown = true;
1341 if (parts.size() >= 5) {
1342 // TODO: remove after 2016-11-03
1343 warningstream << "pwdfield: use field_close_on_enter[name, enabled]" <<
1344 " instead of the 5th param" << std::endl;
1345 field_close_on_enter[name] = is_yes(parts[4]);
1348 m_fields.push_back(spec);
1351 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1354 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1355 core::rect<s32> &rect, bool is_multiline)
1357 bool is_editable = !spec.fname.empty();
1358 if (!is_editable && !is_multiline) {
1359 // spec field id to 0, this stops submit searching for a value that isn't there
1360 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1367 } else if (is_multiline &&
1368 spec.fdefault.empty() && !spec.flabel.empty()) {
1369 // Multiline textareas: swap default and label for backwards compat
1370 spec.flabel.swap(spec.fdefault);
1373 gui::IGUIEditBox *e = nullptr;
1374 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1375 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1377 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1378 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1379 this, spec.fid, rect, is_editable, is_multiline);
1382 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true,
1383 Environment, this, spec.fid, rect, is_editable, true);
1384 } else if (is_editable) {
1385 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this,
1391 auto style = getStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1394 if (is_editable && spec.fname == data->focused_fieldname)
1395 Environment->setFocus(e);
1398 e->setMultiLine(true);
1399 e->setWordWrap(true);
1400 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1403 evt.EventType = EET_KEY_INPUT_EVENT;
1404 evt.KeyInput.Key = KEY_END;
1405 evt.KeyInput.Char = 0;
1406 evt.KeyInput.Control = 0;
1407 evt.KeyInput.Shift = 0;
1408 evt.KeyInput.PressedDown = true;
1412 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1413 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1414 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1415 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1416 e->setDrawBackground(false);
1422 if (!spec.flabel.empty()) {
1423 int font_height = g_fontengine->getTextHeight();
1424 rect.UpperLeftCorner.Y -= font_height;
1425 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1426 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1427 rect, false, true, this, 0);
1430 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1434 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1435 std::vector<std::string> &parts)
1437 std::string name = parts[0];
1438 std::string label = parts[1];
1439 std::string default_val = parts[2];
1441 core::rect<s32> rect;
1443 if (data->explicit_size)
1444 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1446 v2s32 pos = getElementBasePos(nullptr);
1447 pos.Y = (data->simple_field_count + 2) * 60;
1448 v2s32 size = DesiredRect.getSize();
1450 rect = core::rect<s32>(
1451 size.X / 2 - 150, pos.Y,
1452 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1457 default_val = m_form_src->resolveText(default_val);
1460 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1465 utf8_to_wide(unescape_string(default_val)),
1466 258 + m_fields.size()
1469 createTextField(data, spec, rect, false);
1471 m_fields.push_back(spec);
1473 data->simple_field_count++;
1476 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1477 const std::string &type)
1479 std::vector<std::string> v_pos = split(parts[0],',');
1480 std::vector<std::string> v_geom = split(parts[1],',');
1481 std::string name = parts[2];
1482 std::string label = parts[3];
1483 std::string default_val = parts[4];
1485 MY_CHECKPOS(type,0);
1486 MY_CHECKGEOM(type,1);
1491 if (data->real_coordinates) {
1492 pos = getRealCoordinateBasePos(v_pos);
1493 geom = getRealCoordinateGeometry(v_geom);
1495 pos = getElementBasePos(&v_pos);
1498 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1500 if (type == "textarea")
1502 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1503 pos.Y += m_btn_height;
1507 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1508 pos.Y -= m_btn_height;
1509 geom.Y = m_btn_height*2;
1513 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1515 if(!data->explicit_size)
1516 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1519 default_val = m_form_src->resolveText(default_val);
1522 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1527 utf8_to_wide(unescape_string(default_val)),
1528 258 + m_fields.size()
1531 createTextField(data, spec, rect, type == "textarea");
1533 if (parts.size() >= 6) {
1534 // TODO: remove after 2016-11-03
1535 warningstream << "field/textarea: use field_close_on_enter[name, enabled]" <<
1536 " instead of the 6th param" << std::endl;
1537 field_close_on_enter[name] = is_yes(parts[5]);
1540 m_fields.push_back(spec);
1543 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1544 const std::string &type)
1546 std::vector<std::string> parts = split(element,';');
1548 if (parts.size() == 3 || parts.size() == 4) {
1549 parseSimpleField(data,parts);
1553 if ((parts.size() == 5) || (parts.size() == 6) ||
1554 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1556 parseTextArea(data,parts,type);
1559 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1562 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1564 std::vector<std::string> parts = split(element, ';');
1566 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1567 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1571 std::vector<std::string> v_pos = split(parts[0], ',');
1572 std::vector<std::string> v_geom = split(parts[1], ',');
1573 std::string name = parts[2];
1574 std::string text = parts[3];
1576 MY_CHECKPOS("hypertext", 0);
1577 MY_CHECKGEOM("hypertext", 1);
1582 if (data->real_coordinates) {
1583 pos = getRealCoordinateBasePos(v_pos);
1584 geom = getRealCoordinateGeometry(v_geom);
1586 pos = getElementBasePos(&v_pos);
1589 pos.X += stof(v_pos[0]) * spacing.X;
1590 pos.Y += stof(v_pos[1]) * spacing.Y + (m_btn_height * 2);
1592 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1593 geom.Y = (stof(v_geom[1]) * imgsize.Y) - (spacing.Y - imgsize.Y);
1596 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1599 text = m_form_src->resolveText(text);
1603 utf8_to_wide(unescape_string(text)),
1605 258 + m_fields.size()
1608 spec.ftype = f_Unknown;
1610 spec.flabel.c_str(), Environment, this, spec.fid, rect, m_client, m_tsrc);
1612 m_fields.push_back(spec);
1615 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1617 std::vector<std::string> parts = split(element,';');
1619 if ((parts.size() == 2) ||
1620 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1622 std::vector<std::string> v_pos = split(parts[0],',');
1623 std::string text = parts[1];
1625 MY_CHECKPOS("label",0);
1627 if(!data->explicit_size)
1628 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1630 std::vector<std::string> lines = split(text, '\n');
1632 for (unsigned int i = 0; i != lines.size(); i++) {
1633 std::wstring wlabel_colors = translate_string(
1634 utf8_to_wide(unescape_string(lines[i])));
1635 // Without color escapes to get the font dimensions
1636 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1638 core::rect<s32> rect;
1640 if (data->real_coordinates) {
1641 // Lines are spaced at the distance of 1/2 imgsize.
1642 // This alows lines that line up with the new elements
1643 // easily without sacrificing good line distance. If
1644 // it was one whole imgsize, it would have too much
1646 v2s32 pos = getRealCoordinateBasePos(v_pos);
1648 // Labels are positioned by their center, not their top.
1649 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1651 rect = core::rect<s32>(
1653 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1657 // Lines are spaced at the nominal distance of
1658 // 2/5 inventory slot, even if the font doesn't
1659 // quite match that. This provides consistent
1660 // form layout, at the expense of sometimes
1661 // having sub-optimal spacing for the font.
1662 // We multiply by 2 and then divide by 5, rather
1663 // than multiply by 0.4, to get exact results
1664 // in the integer cases: 0.4 is not exactly
1665 // representable in binary floating point.
1667 v2s32 pos = getElementBasePos(nullptr);
1668 pos.X += stof(v_pos[0]) * spacing.X;
1669 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1671 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1673 rect = core::rect<s32>(
1674 pos.X, pos.Y - m_btn_height,
1675 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1676 pos.Y + m_btn_height);
1683 258 + m_fields.size(),
1686 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1687 spec.flabel.c_str(), rect, false, false, this, spec.fid);
1688 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1690 auto style = getStyleForElement("label", spec.fname);
1691 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1692 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1694 m_fields.push_back(spec);
1699 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1700 << "'" << std::endl;
1703 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1705 std::vector<std::string> parts = split(element,';');
1707 if ((parts.size() == 2) ||
1708 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1710 std::vector<std::string> v_pos = split(parts[0],',');
1711 std::wstring text = unescape_translate(
1712 unescape_string(utf8_to_wide(parts[1])));
1714 MY_CHECKPOS("vertlabel",1);
1717 core::rect<s32> rect;
1719 if (data->real_coordinates) {
1720 pos = getRealCoordinateBasePos(v_pos);
1722 // Vertlabels are positioned by center, not left.
1723 pos.X -= imgsize.X / 2;
1725 // We use text.length + 1 because without it, the rect
1726 // isn't quite tall enough and cuts off the text.
1727 rect = core::rect<s32>(pos.X, pos.Y,
1729 pos.Y + font_line_height(m_font) *
1730 (text.length() + 1));
1733 pos = getElementBasePos(&v_pos);
1735 // As above, the length must be one longer. The width of
1736 // the rect (15 pixels) seems rather arbitrary, but
1737 // changing it might break something.
1738 rect = core::rect<s32>(
1739 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1741 font_line_height(m_font) *
1742 (text.length() + 1) +
1743 ((imgsize.Y/2) - m_btn_height));
1746 if(!data->explicit_size)
1747 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1751 for (wchar_t i : text) {
1760 258 + m_fields.size()
1762 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1763 rect, false, false, this, spec.fid);
1764 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1766 auto style = getStyleForElement("vertlabel", spec.fname, "label");
1767 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1768 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1770 m_fields.push_back(spec);
1773 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1776 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1777 const std::string &type)
1779 std::vector<std::string> parts = split(element,';');
1781 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1782 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1784 std::vector<std::string> v_pos = split(parts[0],',');
1785 std::vector<std::string> v_geom = split(parts[1],',');
1786 std::string image_name = parts[2];
1787 std::string name = parts[3];
1788 std::string label = parts[4];
1790 MY_CHECKPOS("imagebutton",0);
1791 MY_CHECKGEOM("imagebutton",1);
1793 bool noclip = false;
1794 bool drawborder = true;
1795 std::string pressed_image_name;
1797 if (parts.size() >= 7) {
1798 if (parts[5] == "true")
1800 if (parts[6] == "false")
1804 if (parts.size() >= 8) {
1805 pressed_image_name = parts[7];
1811 if (data->real_coordinates) {
1812 pos = getRealCoordinateBasePos(v_pos);
1813 geom = getRealCoordinateGeometry(v_geom);
1815 pos = getElementBasePos(&v_pos);
1816 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1817 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1820 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1823 if (!data->explicit_size)
1824 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1826 image_name = unescape_string(image_name);
1827 pressed_image_name = unescape_string(pressed_image_name);
1829 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1834 utf8_to_wide(image_name),
1835 258 + m_fields.size()
1837 spec.ftype = f_Button;
1838 if (type == "image_button_exit")
1839 spec.is_exit = true;
1841 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
1843 if (spec.fname == data->focused_fieldname) {
1844 Environment->setFocus(e);
1847 auto style = getStyleForElement("image_button", spec.fname);
1848 e->setFromStyle(style, m_tsrc);
1850 // We explicitly handle these arguments *after* the style properties in
1851 // order to override them if they are provided
1852 if (!image_name.empty())
1854 video::ITexture *texture = m_tsrc->getTexture(image_name);
1855 e->setForegroundImage(guiScalingImageButton(
1856 Environment->getVideoDriver(), texture, geom.X, geom.Y));
1858 if (!pressed_image_name.empty()) {
1859 video::ITexture *pressed_texture = m_tsrc->getTexture(pressed_image_name);
1860 e->setPressedForegroundImage(guiScalingImageButton(
1861 Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
1863 e->setScaleImage(true);
1865 if (parts.size() >= 7) {
1866 e->setNotClipped(noclip);
1867 e->setDrawBorder(drawborder);
1870 m_fields.push_back(spec);
1874 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
1877 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1879 std::vector<std::string> parts = split(element, ';');
1881 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
1882 data->real_coordinates) || ((parts.size() > 6) &&
1883 (m_formspec_version > FORMSPEC_API_VERSION)))
1885 std::vector<std::string> v_pos = split(parts[0],',');
1887 // If we're using real coordinates, add an extra field for height.
1888 // Width is not here because tabs are the width of the text, and
1889 // there's no reason to change that.
1891 std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
1892 bool auto_width = true;
1893 if (parts.size() == 7) {
1896 v_geom = split(parts[1], ',');
1897 if (v_geom.size() == 1)
1898 v_geom.insert(v_geom.begin(), "1"); // Dummy value
1903 std::string name = parts[i+1];
1904 std::vector<std::string> buttons = split(parts[i+2], ',');
1905 std::string str_index = parts[i+3];
1906 bool show_background = true;
1907 bool show_border = true;
1908 int tab_index = stoi(str_index) - 1;
1910 MY_CHECKPOS("tabheader", 0);
1912 if (parts.size() == 6 + i) {
1913 if (parts[4+i] == "true")
1914 show_background = false;
1915 if (parts[5+i] == "false")
1916 show_border = false;
1923 258 + m_fields.size()
1926 spec.ftype = f_TabHeader;
1931 if (data->real_coordinates) {
1932 pos = getRealCoordinateBasePos(v_pos);
1934 geom = getRealCoordinateGeometry(v_geom);
1935 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
1937 geom.X = DesiredRect.getWidth(); // Set automatic width
1939 MY_CHECKGEOM("tabheader", 1);
1941 v2f32 pos_f = pos_offset * spacing;
1942 pos_f.X += stof(v_pos[0]) * spacing.X;
1943 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
1944 pos = v2s32(pos_f.X, pos_f.Y);
1946 geom.Y = m_btn_height * 2;
1947 geom.X = DesiredRect.getWidth();
1950 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1953 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1954 show_background, show_border, spec.fid);
1955 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1956 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1957 e->setTabHeight(geom.Y);
1959 if (spec.fname == data->focused_fieldname) {
1960 Environment->setFocus(e);
1963 auto style = getStyleForElement("tabheader", name);
1964 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
1966 for (const std::string &button : buttons) {
1967 auto tab = e->addTab(unescape_translate(unescape_string(
1968 utf8_to_wide(button))).c_str(), -1);
1969 if (style.isNotDefault(StyleSpec::BGCOLOR))
1970 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
1972 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1975 if ((tab_index >= 0) &&
1976 (buttons.size() < INT_MAX) &&
1977 (tab_index < (int) buttons.size()))
1978 e->setActiveTab(tab_index);
1980 m_fields.push_back(spec);
1983 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
1984 << element << "'" << std::endl;
1987 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
1990 if (m_client == 0) {
1991 warningstream << "invalid use of item_image_button with m_client==0"
1996 std::vector<std::string> parts = split(element,';');
1998 if ((parts.size() == 5) ||
1999 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2001 std::vector<std::string> v_pos = split(parts[0],',');
2002 std::vector<std::string> v_geom = split(parts[1],',');
2003 std::string item_name = parts[2];
2004 std::string name = parts[3];
2005 std::string label = parts[4];
2007 label = unescape_string(label);
2008 item_name = unescape_string(item_name);
2010 MY_CHECKPOS("itemimagebutton",0);
2011 MY_CHECKGEOM("itemimagebutton",1);
2016 if (data->real_coordinates) {
2017 pos = getRealCoordinateBasePos(v_pos);
2018 geom = getRealCoordinateGeometry(v_geom);
2020 pos = getElementBasePos(&v_pos);
2021 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2022 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2025 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2027 if(!data->explicit_size)
2028 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2030 IItemDefManager *idef = m_client->idef();
2032 item.deSerialize(item_name, idef);
2035 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2036 m_default_tooltip_bgcolor,
2037 m_default_tooltip_color);
2039 // the spec for the button
2042 utf8_to_wide(label),
2043 utf8_to_wide(item_name),
2044 258 + m_fields.size(),
2048 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment, rect, this, spec_btn.fid, spec_btn.flabel.c_str(), item_name, m_client);
2050 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2051 e_btn->setFromStyle(style, m_tsrc);
2053 if (spec_btn.fname == data->focused_fieldname) {
2054 Environment->setFocus(e_btn);
2057 spec_btn.ftype = f_Button;
2058 rect += data->basepos-padding;
2059 spec_btn.rect = rect;
2060 m_fields.push_back(spec_btn);
2063 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2066 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2068 std::vector<std::string> parts = split(element,';');
2070 if ((parts.size() == 3) ||
2071 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2073 std::vector<std::string> v_pos = split(parts[0],',');
2074 std::vector<std::string> v_geom = split(parts[1],',');
2076 MY_CHECKPOS("box",0);
2077 MY_CHECKGEOM("box",1);
2082 if (data->real_coordinates) {
2083 pos = getRealCoordinateBasePos(v_pos);
2084 geom = getRealCoordinateGeometry(v_geom);
2086 pos = getElementBasePos(&v_pos);
2087 geom.X = stof(v_geom[0]) * spacing.X;
2088 geom.Y = stof(v_geom[1]) * spacing.Y;
2091 video::SColor tmp_color;
2093 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2098 258 + m_fields.size(),
2103 core::rect<s32> rect(pos, pos + geom);
2105 GUIBox *e = new GUIBox(Environment, this, spec.fid, rect, tmp_color);
2107 e->setNotClipped(true);
2111 m_fields.push_back(spec);
2114 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2118 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2121 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2123 std::vector<std::string> parts = split(element,';');
2124 const u32 parameter_count = parts.size();
2126 if ((parameter_count > 2 && m_formspec_version < 3) ||
2127 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2128 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2129 << element << "'" << std::endl;
2134 if (parameter_count >= 1 && parts[0] != "")
2135 parseColorString(parts[0], m_bgcolor, false);
2138 if (parameter_count >= 2) {
2139 if (parts[1] == "both") {
2140 m_bgnonfullscreen = true;
2141 m_bgfullscreen = true;
2142 } else if (parts[1] == "neither") {
2143 m_bgnonfullscreen = false;
2144 m_bgfullscreen = false;
2145 } else if (parts[1] != "" || m_formspec_version < 3) {
2146 m_bgfullscreen = is_yes(parts[1]);
2147 m_bgnonfullscreen = !m_bgfullscreen;
2152 if (parameter_count >= 3 && parts[2] != "")
2153 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2156 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2158 std::vector<std::string> parts = split(element,';');
2160 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2161 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2163 parseColorString(parts[0], m_slotbg_n, false);
2164 parseColorString(parts[1], m_slotbg_h, false);
2166 if (parts.size() >= 3) {
2167 if (parseColorString(parts[2], m_slotbordercolor, false)) {
2168 m_slotborder = true;
2171 if (parts.size() == 5) {
2172 video::SColor tmp_color;
2174 if (parseColorString(parts[3], tmp_color, false))
2175 m_default_tooltip_bgcolor = tmp_color;
2176 if (parseColorString(parts[4], tmp_color, false))
2177 m_default_tooltip_color = tmp_color;
2181 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2184 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2186 std::vector<std::string> parts = split(element,';');
2187 if (parts.size() < 2) {
2188 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2189 << element << "'" << std::endl;
2193 // Get mode and check size
2194 bool rect_mode = parts[0].find(',') != std::string::npos;
2195 size_t base_size = rect_mode ? 3 : 2;
2196 if (parts.size() != base_size && parts.size() != base_size + 2) {
2197 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2198 << element << "'" << std::endl;
2203 video::SColor bgcolor = m_default_tooltip_bgcolor;
2204 video::SColor color = m_default_tooltip_color;
2205 if (parts.size() == base_size + 2 &&
2206 (!parseColorString(parts[base_size], bgcolor, false) ||
2207 !parseColorString(parts[base_size + 1], color, false))) {
2208 errorstream << "Invalid color in tooltip element(" << parts.size()
2209 << "): '" << element << "'" << std::endl;
2213 // Make tooltip spec
2214 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2215 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2219 std::vector<std::string> v_pos = split(parts[0], ',');
2220 std::vector<std::string> v_geom = split(parts[1], ',');
2222 MY_CHECKPOS("tooltip", 0);
2223 MY_CHECKGEOM("tooltip", 1);
2228 if (data->real_coordinates) {
2229 pos = getRealCoordinateBasePos(v_pos);
2230 geom = getRealCoordinateGeometry(v_geom);
2232 pos = getElementBasePos(&v_pos);
2233 geom.X = stof(v_geom[0]) * spacing.X;
2234 geom.Y = stof(v_geom[1]) * spacing.Y;
2237 FieldSpec fieldspec(
2241 258 + m_fields.size()
2244 core::rect<s32> rect(pos, pos + geom);
2246 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2247 this, fieldspec.fid, rect);
2249 // the element the rect tooltip is bound to should not block mouse-clicks
2250 e->setVisible(false);
2252 m_fields.push_back(fieldspec);
2253 m_tooltip_rects.emplace_back(e, spec);
2256 m_tooltips[parts[0]] = spec;
2260 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2266 std::vector<std::string> parts = split(data,'[');
2268 if (parts.size() < 2) {
2272 if (trim(parts[0]) != "formspec_version") {
2276 if (is_number(parts[1])) {
2277 m_formspec_version = mystoi(parts[1]);
2284 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2286 if (element.empty())
2289 std::vector<std::string> parts = split(element,'[');
2291 if (parts.size() < 2)
2294 std::string type = trim(parts[0]);
2295 std::string description = trim(parts[1]);
2297 if (type != "size" && type != "invsize")
2300 if (type == "invsize")
2301 log_deprecated("Deprecated formspec element \"invsize\" is used");
2303 parseSize(data, description);
2308 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2310 if (element.empty())
2313 std::vector<std::string> parts = split(element, '[');
2315 if (parts.size() != 2)
2318 std::string type = trim(parts[0]);
2319 std::string description = trim(parts[1]);
2321 if (type != "position")
2324 parsePosition(data, description);
2329 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2331 std::vector<std::string> parts = split(element, ',');
2333 if (parts.size() == 2) {
2334 data->offset.X = stof(parts[0]);
2335 data->offset.Y = stof(parts[1]);
2339 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2342 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2344 if (element.empty())
2347 std::vector<std::string> parts = split(element, '[');
2349 if (parts.size() != 2)
2352 std::string type = trim(parts[0]);
2353 std::string description = trim(parts[1]);
2355 if (type != "anchor")
2358 parseAnchor(data, description);
2363 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2365 std::vector<std::string> parts = split(element, ',');
2367 if (parts.size() == 2) {
2368 data->anchor.X = stof(parts[0]);
2369 data->anchor.Y = stof(parts[1]);
2373 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2374 << "'" << std::endl;
2377 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2379 std::vector<std::string> parts = split(element, ';');
2381 if (parts.size() < 2) {
2382 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2383 << "'" << std::endl;
2387 std::string selector = trim(parts[0]);
2388 if (selector.empty()) {
2389 errorstream << "Invalid style element (Selector required): '" << element
2390 << "'" << std::endl;
2396 for (size_t i = 1; i < parts.size(); i++) {
2397 size_t equal_pos = parts[i].find('=');
2398 if (equal_pos == std::string::npos) {
2399 errorstream << "Invalid style element (Property missing value): '" << element
2400 << "'" << std::endl;
2404 std::string propname = trim(parts[i].substr(0, equal_pos));
2405 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2407 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2409 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2410 if (prop == StyleSpec::NONE) {
2411 if (property_warned.find(propname) != property_warned.end()) {
2412 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2414 << "'" << std::endl;
2415 property_warned.insert(propname);
2420 spec.set(prop, value);
2424 theme_by_type[selector] |= spec;
2426 theme_by_name[selector] |= spec;
2432 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2435 if (element.empty())
2438 if (parseVersionDirect(element))
2441 std::vector<std::string> parts = split(element,'[');
2443 // ugly workaround to keep compatibility
2444 if (parts.size() > 2) {
2445 if (trim(parts[0]) == "image") {
2446 for (unsigned int i=2;i< parts.size(); i++) {
2447 parts[1] += "[" + parts[i];
2453 if (parts.size() < 2) {
2457 std::string type = trim(parts[0]);
2458 std::string description = trim(parts[1]);
2460 if (type == "container") {
2461 parseContainer(data, description);
2465 if (type == "container_end") {
2466 parseContainerEnd(data);
2470 if (type == "list") {
2471 parseList(data, description);
2475 if (type == "listring") {
2476 parseListRing(data, description);
2480 if (type == "checkbox") {
2481 parseCheckbox(data, description);
2485 if (type == "image") {
2486 parseImage(data, description);
2490 if (type == "item_image") {
2491 parseItemImage(data, description);
2495 if (type == "button" || type == "button_exit") {
2496 parseButton(data, description, type);
2500 if (type == "background" || type == "background9") {
2501 parseBackground(data, description);
2505 if (type == "tableoptions"){
2506 parseTableOptions(data,description);
2510 if (type == "tablecolumns"){
2511 parseTableColumns(data,description);
2515 if (type == "table"){
2516 parseTable(data,description);
2520 if (type == "textlist"){
2521 parseTextList(data,description);
2525 if (type == "dropdown"){
2526 parseDropDown(data,description);
2530 if (type == "field_close_on_enter") {
2531 parseFieldCloseOnEnter(data, description);
2535 if (type == "pwdfield") {
2536 parsePwdField(data,description);
2540 if ((type == "field") || (type == "textarea")){
2541 parseField(data,description,type);
2545 if (type == "hypertext") {
2546 parseHyperText(data,description);
2550 if (type == "label") {
2551 parseLabel(data,description);
2555 if (type == "vertlabel") {
2556 parseVertLabel(data,description);
2560 if (type == "item_image_button") {
2561 parseItemImageButton(data,description);
2565 if ((type == "image_button") || (type == "image_button_exit")) {
2566 parseImageButton(data,description,type);
2570 if (type == "tabheader") {
2571 parseTabHeader(data,description);
2575 if (type == "box") {
2576 parseBox(data,description);
2580 if (type == "bgcolor") {
2581 parseBackgroundColor(data,description);
2585 if (type == "listcolors") {
2586 parseListColors(data,description);
2590 if (type == "tooltip") {
2591 parseTooltip(data,description);
2595 if (type == "scrollbar") {
2596 parseScrollBar(data, description);
2600 if (type == "real_coordinates") {
2601 data->real_coordinates = is_yes(description);
2605 if (type == "style") {
2606 parseStyle(data, description, false);
2610 if (type == "style_type") {
2611 parseStyle(data, description, true);
2615 if (type == "scrollbaroptions") {
2616 parseScrollBarOptions(data, description);
2621 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2625 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2627 /* useless to regenerate without a screensize */
2628 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2635 for (auto &m_table : m_tables) {
2636 std::string tablename = m_table.first.fname;
2637 GUITable *table = m_table.second;
2638 mydata.table_dyndata[tablename] = table->getDynamicData();
2642 if (!m_focused_element.empty())
2643 mydata.focused_fieldname = m_focused_element;
2646 gui::IGUIElement *focused_element = Environment->getFocus();
2647 if (focused_element && focused_element->getParent() == this) {
2648 s32 focused_id = focused_element->getID();
2649 if (focused_id > 257) {
2650 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2651 if (field.fid == focused_id) {
2652 mydata.focused_fieldname = field.fname;
2662 for (auto &table_it : m_tables)
2663 table_it.second->drop();
2664 for (auto &inventorylist_it : m_inventorylists)
2665 inventorylist_it.e->drop();
2666 for (auto &checkbox_it : m_checkboxes)
2667 checkbox_it.second->drop();
2668 for (auto &scrollbar_it : m_scrollbars)
2669 scrollbar_it.second->drop();
2670 for (auto &background_it : m_backgrounds)
2671 background_it->drop();
2672 for (auto &tooltip_rect_it : m_tooltip_rects)
2673 tooltip_rect_it.first->drop();
2675 mydata.size= v2s32(100,100);
2676 mydata.screensize = screensize;
2677 mydata.offset = v2f32(0.5f, 0.5f);
2678 mydata.anchor = v2f32(0.5f, 0.5f);
2679 mydata.simple_field_count = 0;
2681 // Base position of contents of form
2682 mydata.basepos = getBasePos();
2684 /* Convert m_init_draw_spec to m_inventorylists */
2686 m_inventorylists.clear();
2687 m_backgrounds.clear();
2689 m_checkboxes.clear();
2690 m_scrollbars.clear();
2693 m_tooltip_rects.clear();
2694 m_inventory_rings.clear();
2695 m_dropdowns.clear();
2696 theme_by_name.clear();
2697 theme_by_type.clear();
2699 m_bgnonfullscreen = true;
2700 m_bgfullscreen = false;
2702 m_formspec_version = 1;
2705 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2706 m_bgcolor = video::SColor(
2707 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2708 clamp_u8(myround(formspec_bgcolor.X)),
2709 clamp_u8(myround(formspec_bgcolor.Y)),
2710 clamp_u8(myround(formspec_bgcolor.Z))
2715 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2716 m_fullscreen_bgcolor = video::SColor(
2717 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2718 clamp_u8(myround(formspec_bgcolor.X)),
2719 clamp_u8(myround(formspec_bgcolor.Y)),
2720 clamp_u8(myround(formspec_bgcolor.Z))
2724 m_slotbg_n = video::SColor(255,128,128,128);
2725 m_slotbg_h = video::SColor(255,192,192,192);
2727 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2728 m_default_tooltip_color = video::SColor(255,255,255,255);
2730 m_slotbordercolor = video::SColor(200,0,0,0);
2731 m_slotborder = false;
2735 assert(!m_tooltip_element);
2736 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2737 m_tooltip_element = gui::StaticText::add(Environment, L"",
2738 core::rect<s32>(0, 0, 110, 18));
2739 m_tooltip_element->enableOverrideColor(true);
2740 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2741 m_tooltip_element->setDrawBackground(true);
2742 m_tooltip_element->setDrawBorder(true);
2743 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2744 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2745 m_tooltip_element->setWordWrap(false);
2746 //we're not parent so no autograb for this one!
2747 m_tooltip_element->grab();
2750 std::vector<std::string> elements = split(m_formspec_string,']');
2753 /* try to read version from first element only */
2754 if (!elements.empty()) {
2755 if (parseVersionDirect(elements[0])) {
2760 /* we need size first in order to calculate image scale */
2761 mydata.explicit_size = false;
2762 for (; i< elements.size(); i++) {
2763 if (!parseSizeDirect(&mydata, elements[i])) {
2768 /* "position" element is always after "size" element if it used */
2769 for (; i< elements.size(); i++) {
2770 if (!parsePositionDirect(&mydata, elements[i])) {
2775 /* "anchor" element is always after "position" (or "size" element) if it used */
2776 for (; i< elements.size(); i++) {
2777 if (!parseAnchorDirect(&mydata, elements[i])) {
2782 /* "no_prepend" element is always after "position" (or "size" element) if it used */
2783 bool enable_prepends = true;
2784 for (; i < elements.size(); i++) {
2785 if (elements[i].empty())
2788 std::vector<std::string> parts = split(elements[i], '[');
2789 if (trim(parts[0]) == "no_prepend")
2790 enable_prepends = false;
2795 /* Copy of the "real_coordinates" element for after the form size. */
2796 mydata.real_coordinates = m_formspec_version >= 2;
2797 for (; i < elements.size(); i++) {
2798 std::vector<std::string> parts = split(elements[i], '[');
2799 std::string name = trim(parts[0]);
2800 if (name != "real_coordinates" || parts.size() != 2)
2801 break; // Invalid format
2803 mydata.real_coordinates = is_yes(trim(parts[1]));
2806 if (mydata.explicit_size) {
2807 // compute scaling for specified form size
2809 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2810 v2u32 delta = current_screensize - m_lockscreensize;
2812 if (current_screensize.Y > m_lockscreensize.Y)
2817 if (current_screensize.X > m_lockscreensize.X)
2822 offset = v2s32(delta.X,delta.Y);
2824 mydata.screensize = m_lockscreensize;
2826 offset = v2s32(0,0);
2829 double gui_scaling = g_settings->getFloat("gui_scaling");
2830 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2834 // In fixed-size mode, inventory image size
2835 // is 0.53 inch multiplied by the gui_scaling
2836 // config parameter. This magic size is chosen
2837 // to make the main menu (15.5 inventory images
2838 // wide, including border) just fit into the
2839 // default window (800 pixels wide) at 96 DPI
2840 // and default scaling (1.00).
2841 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2843 // In variable-size mode, we prefer to make the
2844 // inventory image size 1/15 of screen height,
2845 // multiplied by the gui_scaling config parameter.
2846 // If the preferred size won't fit the whole
2847 // form on the screen, either horizontally or
2848 // vertically, then we scale it down to fit.
2849 // (The magic numbers in the computation of what
2850 // fits arise from the scaling factors in the
2851 // following stanza, including the form border,
2852 // help text space, and 0.1 inventory slot spare.)
2853 // However, a minimum size is also set, that
2854 // the image size can't be less than 0.3 inch
2855 // multiplied by gui_scaling, even if this means
2856 // the form doesn't fit the screen.
2858 // For mobile devices these magic numbers are
2859 // different and forms should always use the
2860 // maximum screen space available.
2861 double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
2862 double fitx_imgsize = mydata.screensize.X /
2863 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
2864 double fity_imgsize = mydata.screensize.Y /
2865 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
2866 use_imgsize = MYMIN(prefer_imgsize,
2867 MYMIN(fitx_imgsize, fity_imgsize));
2869 double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
2870 double fitx_imgsize = mydata.screensize.X /
2871 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
2872 double fity_imgsize = mydata.screensize.Y /
2873 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
2874 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2875 double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2876 use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2877 MYMIN(fitx_imgsize, fity_imgsize)));
2881 // Everything else is scaled in proportion to the
2882 // inventory image size. The inventory slot spacing
2883 // is 5/4 image size horizontally and 15/13 image size
2884 // vertically. The padding around the form (incorporating
2885 // the border of the outer inventory slots) is 3/8
2886 // image size. Font height (baseline to baseline)
2887 // is 2/5 vertical inventory slot spacing, and button
2888 // half-height is 7/8 of font height.
2889 imgsize = v2s32(use_imgsize, use_imgsize);
2890 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2891 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2892 m_btn_height = use_imgsize*15.0/13 * 0.35;
2894 m_font = g_fontengine->getFont();
2896 if (mydata.real_coordinates) {
2897 mydata.size = v2s32(
2898 mydata.invsize.X*imgsize.X,
2899 mydata.invsize.Y*imgsize.Y
2902 mydata.size = v2s32(
2903 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2904 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2908 DesiredRect = mydata.rect = core::rect<s32>(
2909 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2910 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2911 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2912 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2915 // Non-size[] form must consist only of text fields and
2916 // implicit "Proceed" button. Use default font, and
2917 // temporary form size which will be recalculated below.
2918 m_font = g_fontengine->getFont();
2919 m_btn_height = font_line_height(m_font) * 0.875;
2920 DesiredRect = core::rect<s32>(
2921 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2922 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2923 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2924 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2927 recalculateAbsolutePosition(false);
2928 mydata.basepos = getBasePos();
2929 m_tooltip_element->setOverrideFont(m_font);
2931 gui::IGUISkin *skin = Environment->getSkin();
2933 gui::IGUIFont *old_font = skin->getFont();
2934 skin->setFont(m_font);
2936 pos_offset = v2f32();
2938 // used for formspec versions < 3
2939 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
2941 if (enable_prepends) {
2942 // Backup the coordinates so that prepends can use the coordinates of choice.
2943 bool rc_backup = mydata.real_coordinates;
2944 u16 version_backup = m_formspec_version;
2945 mydata.real_coordinates = false; // Old coordinates by default.
2947 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
2948 for (const auto &element : prepend_elements)
2949 parseElement(&mydata, element);
2951 // legacy sorting for formspec versions < 3
2952 if (m_formspec_version >= 3)
2953 // prepends do not need to be reordered
2954 legacy_sort_start = Children.getLast();
2955 else if (version_backup >= 3)
2956 // only prepends elements have to be reordered
2957 legacySortElements(legacy_sort_start);
2959 m_formspec_version = version_backup;
2960 mydata.real_coordinates = rc_backup; // Restore coordinates
2963 for (; i< elements.size(); i++) {
2964 parseElement(&mydata, elements[i]);
2967 if (!container_stack.empty()) {
2968 errorstream << "Invalid formspec string: container was never closed!"
2972 // If there are fields without explicit size[], add a "Proceed"
2973 // button and adjust size to fit all the fields.
2974 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
2975 mydata.rect = core::rect<s32>(
2976 mydata.screensize.X / 2 - 580 / 2,
2977 mydata.screensize.Y / 2 - 300 / 2,
2978 mydata.screensize.X / 2 + 580 / 2,
2979 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
2982 DesiredRect = mydata.rect;
2983 recalculateAbsolutePosition(false);
2984 mydata.basepos = getBasePos();
2987 v2s32 pos = mydata.basepos;
2988 pos.Y = (mydata.simple_field_count + 2) * 60;
2990 v2s32 size = DesiredRect.getSize();
2991 mydata.rect = core::rect<s32>(
2992 size.X / 2 - 70, pos.Y,
2993 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
2995 const wchar_t *text = wgettext("Proceed");
2996 GUIButton::addButton(Environment, mydata.rect, this, 257, text);
3001 //set initial focus if parser didn't set it
3002 focused_element = Environment->getFocus();
3003 if (!focused_element
3004 || !isMyChild(focused_element)
3005 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3008 skin->setFont(old_font);
3011 if (m_formspec_version < 3)
3012 legacySortElements(legacy_sort_start);
3015 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3018 Draw order for formspec_version <= 2:
3022 0 All other elements
3024 2 item_image, item_image_button
3029 if (from == Children.end())
3030 from = Children.begin();
3034 core::list<IGUIElement *>::Iterator to = Children.end();
3035 // 1: Copy into a sortable container
3036 std::vector<IGUIElement *> elements;
3037 for (auto it = from; it != to; ++it)
3038 elements.emplace_back(*it);
3040 // 2: Sort the container
3041 std::stable_sort(elements.begin(), elements.end(),
3042 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3043 const FieldSpec *spec_a = getSpecByID(a->getID());
3044 const FieldSpec *spec_b = getSpecByID(b->getID());
3045 return spec_a && spec_b &&
3046 spec_a->priority < spec_b->priority;
3049 // 3: Re-assign the pointers
3050 for (auto e : elements) {
3057 bool GUIFormSpecMenu::getAndroidUIInput()
3059 if (!hasAndroidUIInput())
3062 std::string fieldname = m_jni_field_name;
3063 m_jni_field_name.clear();
3065 for(std::vector<FieldSpec>::iterator iter = m_fields.begin();
3066 iter != m_fields.end(); ++iter) {
3068 if (iter->fname != fieldname) {
3071 IGUIElement *tochange = getElementFromId(iter->fid, true);
3073 if (tochange == 0) {
3077 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
3081 std::string text = porting::getInputDialogValue();
3083 ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
3089 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3091 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3093 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3094 core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3095 v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3096 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
3097 s32 item_i = i + s.start_item_i;
3101 if (s.real_coordinates) {
3102 x = (i%s.geom.X) * (imgsize.X * 1.25);
3103 y = (i/s.geom.X) * (imgsize.Y * 1.25);
3105 x = (i%s.geom.X) * spacing.X;
3106 y = (i/s.geom.X) * spacing.Y;
3109 core::rect<s32> rect = imgrect + base_pos + p0;
3110 rect.clipAgainst(clipping_rect);
3111 if (rect.getArea() > 0 && rect.isPointInside(p))
3112 return ItemSpec(s.inventoryloc, s.listname, item_i);
3116 return ItemSpec(InventoryLocation(), "", -1);
3119 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer,
3122 video::IVideoDriver* driver = Environment->getVideoDriver();
3124 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3126 warningstream<<"GUIFormSpecMenu::drawList(): "
3127 << "The inventory location "
3128 << "\"" << s.inventoryloc.dump() << "\" doesn't exist anymore"
3132 InventoryList *ilist = inv->getList(s.listname);
3134 warningstream << "GUIFormSpecMenu::drawList(): "
3135 << "The inventory list \"" << s.listname << "\" @ \""
3136 << s.inventoryloc.dump() << "\" doesn't exist anymore"
3141 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3142 core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3143 v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3145 for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) {
3146 s32 item_i = i + s.start_item_i;
3147 if (item_i >= (s32)ilist->getSize())
3152 if (s.real_coordinates) {
3153 x = (i%s.geom.X) * (imgsize.X * 1.25);
3154 y = (i/s.geom.X) * (imgsize.Y * 1.25);
3156 x = (i%s.geom.X) * spacing.X;
3157 y = (i/s.geom.X) * spacing.Y;
3160 core::rect<s32> rect = imgrect + base_pos + p;
3161 ItemStack item = ilist->getItem(item_i);
3163 bool selected = m_selected_item
3164 && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
3165 && m_selected_item->listname == s.listname
3166 && m_selected_item->i == item_i;
3167 core::rect<s32> clipped_rect(rect);
3168 clipped_rect.clipAgainst(clipping_rect);
3169 bool hovering = clipped_rect.getArea() > 0 &&
3170 clipped_rect.isPointInside(m_pointer);
3171 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
3172 (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
3176 item_hovered = true;
3177 driver->draw2DRectangle(m_slotbg_h, rect, &clipping_rect);
3179 driver->draw2DRectangle(m_slotbg_n, rect, &clipping_rect);
3183 //Draw inv slot borders
3185 s32 x1 = rect.UpperLeftCorner.X;
3186 s32 y1 = rect.UpperLeftCorner.Y;
3187 s32 x2 = rect.LowerRightCorner.X;
3188 s32 y2 = rect.LowerRightCorner.Y;
3190 driver->draw2DRectangle(m_slotbordercolor,
3191 core::rect<s32>(v2s32(x1 - border, y1 - border),
3192 v2s32(x2 + border, y1)), &clipping_rect);
3193 driver->draw2DRectangle(m_slotbordercolor,
3194 core::rect<s32>(v2s32(x1 - border, y2),
3195 v2s32(x2 + border, y2 + border)), &clipping_rect);
3196 driver->draw2DRectangle(m_slotbordercolor,
3197 core::rect<s32>(v2s32(x1 - border, y1),
3198 v2s32(x1, y2)), &clipping_rect);
3199 driver->draw2DRectangle(m_slotbordercolor,
3200 core::rect<s32>(v2s32(x2, y1),
3201 v2s32(x2 + border, y2)), &clipping_rect);
3206 item.takeItem(m_selected_amount);
3208 if (!item.empty()) {
3210 drawItemStack(driver, m_font, item,
3211 rect, &clipping_rect, m_client, rotation_kind);
3213 if (hovering && !m_selected_item) {
3214 std::string tooltip = item.getDescription(m_client->idef());
3215 if (m_tooltip_append_itemname)
3216 tooltip += "\n[" + item.name + "]";
3217 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3218 m_default_tooltip_bgcolor);
3225 void GUIFormSpecMenu::drawSelectedItem()
3227 video::IVideoDriver* driver = Environment->getVideoDriver();
3229 if (!m_selected_item) {
3230 // reset rotation time
3231 drawItemStack(driver, m_font, ItemStack(),
3232 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3233 m_client, IT_ROT_DRAGGED);
3237 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3239 InventoryList *list = inv->getList(m_selected_item->listname);
3241 ItemStack stack = list->getItem(m_selected_item->i);
3242 stack.count = m_selected_amount;
3244 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3245 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3246 rect.constrainTo(driver->getViewPort());
3247 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3250 void GUIFormSpecMenu::drawMenu()
3253 const std::string &newform = m_form_src->getForm();
3254 if (newform != m_formspec_string) {
3255 m_formspec_string = newform;
3256 regenerateGui(m_screensize_old);
3260 gui::IGUISkin* skin = Environment->getSkin();
3261 sanity_check(skin != NULL);
3262 gui::IGUIFont *old_font = skin->getFont();
3263 skin->setFont(m_font);
3265 updateSelectedItem();
3267 video::IVideoDriver* driver = Environment->getVideoDriver();
3270 Draw background color
3272 v2u32 screenSize = driver->getScreenSize();
3273 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3276 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3277 if (m_bgnonfullscreen)
3278 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3281 Draw rect_mode tooltip
3283 m_tooltip_element->setVisible(false);
3285 for (const auto &pair : m_tooltip_rects) {
3286 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3287 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3288 const std::wstring &text = pair.second.tooltip;
3289 if (!text.empty()) {
3290 showTooltip(text, pair.second.color, pair.second.bgcolor);
3299 for (gui::IGUIElement *e : m_backgrounds) {
3300 e->setVisible(true);
3302 e->setVisible(false);
3308 gui::IGUIElement::draw();
3312 Layer 0: Item slot rectangles
3313 Layer 1: Item images; prepare tooltip
3315 bool item_hovered = false;
3316 for (int layer = 0; layer < 2; layer++) {
3317 for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
3318 drawList(spec, layer, item_hovered);
3321 if (!item_hovered) {
3322 // reset rotation time
3323 drawItemStack(driver, m_font, ItemStack(),
3324 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3325 NULL, m_client, IT_ROT_HOVERED);
3328 /* TODO find way to show tooltips on touchscreen */
3329 #ifndef HAVE_TOUCHSCREENGUI
3330 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3334 Draw fields/buttons tooltips
3336 gui::IGUIElement *hovered =
3337 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3339 if (hovered != NULL) {
3340 s32 id = hovered->getID();
3344 m_old_tooltip_id = id;
3346 if (id == m_old_tooltip_id) {
3347 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3349 m_hovered_time = porting::getTimeMs();
3350 m_old_tooltip_id = id;
3354 // Find and update the current tooltip
3355 if (id != -1 && delta >= m_tooltip_show_delay) {
3356 for (const FieldSpec &field : m_fields) {
3358 if (field.fid != id)
3361 const std::wstring &text = m_tooltips[field.fname].tooltip;
3363 showTooltip(text, m_tooltips[field.fname].color,
3364 m_tooltips[field.fname].bgcolor);
3371 m_tooltip_element->draw();
3374 Draw dragged item stack
3378 skin->setFont(old_font);
3382 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3383 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3385 const std::wstring ntext = translate_string(text);
3386 m_tooltip_element->setOverrideColor(color);
3387 m_tooltip_element->setBackgroundColor(bgcolor);
3388 setStaticText(m_tooltip_element, ntext.c_str());
3390 // Tooltip size and offset
3391 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3392 #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
3393 std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
3394 s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
3396 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3398 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3399 int tooltip_offset_x = m_btn_height;
3400 int tooltip_offset_y = m_btn_height;
3402 tooltip_offset_x *= 3;
3403 tooltip_offset_y = 0;
3404 if (m_pointer.X > (s32)screenSize.X / 2)
3405 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3408 // Calculate and set the tooltip position
3409 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3410 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3411 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3412 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3413 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3414 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3416 m_tooltip_element->setRelativePosition(
3418 core::position2d<s32>(tooltip_x, tooltip_y),
3419 core::dimension2d<s32>(tooltip_width, tooltip_height)
3423 // Display the tooltip
3424 m_tooltip_element->setVisible(true);
3425 bringToFront(m_tooltip_element);
3428 void GUIFormSpecMenu::updateSelectedItem()
3430 verifySelectedItem();
3432 // If craftresult is nonempty and nothing else is selected, select it now.
3433 if (!m_selected_item) {
3434 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3435 if (s.listname != "craftpreview")
3438 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3442 InventoryList *list = inv->getList("craftresult");
3444 if (!list || list->getSize() == 0)
3447 const ItemStack &item = list->getItem(0);
3451 // Grab selected item from the crafting result list
3452 m_selected_item = new ItemSpec;
3453 m_selected_item->inventoryloc = s.inventoryloc;
3454 m_selected_item->listname = "craftresult";
3455 m_selected_item->i = 0;
3456 m_selected_amount = item.count;
3457 m_selected_dragging = false;
3462 // If craftresult is selected, keep the whole stack selected
3463 if (m_selected_item && m_selected_item->listname == "craftresult")
3464 m_selected_amount = verifySelectedItem().count;
3467 ItemStack GUIFormSpecMenu::verifySelectedItem()
3469 // If the selected stack has become empty for some reason, deselect it.
3470 // If the selected stack has become inaccessible, deselect it.
3471 // If the selected stack has become smaller, adjust m_selected_amount.
3472 // Return the selected stack.
3476 if(m_selected_item->isValid())
3478 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3481 InventoryList *list = inv->getList(m_selected_item->listname);
3482 if(list && (u32) m_selected_item->i < list->getSize())
3484 ItemStack stack = list->getItem(m_selected_item->i);
3485 if (!m_selected_swap.empty()) {
3486 if (m_selected_swap.name == stack.name &&
3487 m_selected_swap.count == stack.count)
3488 m_selected_swap.clear();
3490 m_selected_amount = std::min(m_selected_amount, stack.count);
3499 // selection was not valid
3500 delete m_selected_item;
3501 m_selected_item = NULL;
3502 m_selected_amount = 0;
3503 m_selected_dragging = false;
3508 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3514 if (quitmode == quit_mode_accept) {
3515 fields["quit"] = "true";
3518 if (quitmode == quit_mode_cancel) {
3519 fields["quit"] = "true";
3520 m_text_dst->gotText(fields);
3524 if (current_keys_pending.key_down) {
3525 fields["key_down"] = "true";
3526 current_keys_pending.key_down = false;
3529 if (current_keys_pending.key_up) {
3530 fields["key_up"] = "true";
3531 current_keys_pending.key_up = false;
3534 if (current_keys_pending.key_enter) {
3535 fields["key_enter"] = "true";
3536 current_keys_pending.key_enter = false;
3539 if (!current_field_enter_pending.empty()) {
3540 fields["key_enter_field"] = current_field_enter_pending;
3541 current_field_enter_pending = "";
3544 if (current_keys_pending.key_escape) {
3545 fields["key_escape"] = "true";
3546 current_keys_pending.key_escape = false;
3549 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3551 std::string name = s.fname;
3552 if (s.ftype == f_Button) {
3553 fields[name] = wide_to_utf8(s.flabel);
3554 } else if (s.ftype == f_Table) {
3555 GUITable *table = getTable(s.fname);
3557 fields[name] = table->checkEvent();
3560 else if(s.ftype == f_DropDown) {
3561 // no dynamic cast possible due to some distributions shipped
3562 // without rtti support in irrlicht
3563 IGUIElement *element = getElementFromId(s.fid, true);
3564 gui::IGUIComboBox *e = NULL;
3565 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3566 e = static_cast<gui::IGUIComboBox*>(element);
3568 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3569 << "field without dropdown element" << std::endl;
3572 s32 selected = e->getSelected();
3573 if (selected >= 0) {
3574 std::vector<std::string> *dropdown_values =
3575 getDropDownValues(s.fname);
3576 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3577 fields[name] = (*dropdown_values)[selected];
3581 else if (s.ftype == f_TabHeader) {
3582 // no dynamic cast possible due to some distributions shipped
3583 // without rttzi support in irrlicht
3584 IGUIElement *element = getElementFromId(s.fid, true);
3585 gui::IGUITabControl *e = nullptr;
3586 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3587 e = static_cast<gui::IGUITabControl *>(element);
3591 std::stringstream ss;
3592 ss << (e->getActiveTab() +1);
3593 fields[name] = ss.str();
3596 else if (s.ftype == f_CheckBox) {
3597 // no dynamic cast possible due to some distributions shipped
3598 // without rtti support in irrlicht
3599 IGUIElement *element = getElementFromId(s.fid, true);
3600 gui::IGUICheckBox *e = nullptr;
3601 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3602 e = static_cast<gui::IGUICheckBox*>(element);
3607 fields[name] = "true";
3609 fields[name] = "false";
3612 else if (s.ftype == f_ScrollBar) {
3613 // no dynamic cast possible due to some distributions shipped
3614 // without rtti support in irrlicht
3615 IGUIElement *element = getElementFromId(s.fid, true);
3616 GUIScrollBar *e = nullptr;
3617 if (element && element->getType() == gui::EGUIET_ELEMENT)
3618 e = static_cast<GUIScrollBar *>(element);
3621 std::stringstream os;
3623 if (s.fdefault == L"Changed")
3624 fields[name] = "CHG:" + os.str();
3626 fields[name] = "VAL:" + os.str();
3630 IGUIElement *e = getElementFromId(s.fid, true);
3632 fields[name] = wide_to_utf8(e->getText());
3637 m_text_dst->gotText(fields);
3641 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
3643 while(tocheck != NULL) {
3644 if (tocheck == parent) {
3647 tocheck = tocheck->getParent();
3652 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3654 // The IGUITabControl renders visually using the skin's selected
3655 // font, which we override for the duration of form drawing,
3656 // but computes tab hotspots based on how it would have rendered
3657 // using the font that is selected at the time of button release.
3658 // To make these two consistent, temporarily override the skin's
3659 // font while the IGUITabControl is processing the event.
3660 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3661 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3662 s32 x = event.MouseInput.X;
3663 s32 y = event.MouseInput.Y;
3664 gui::IGUIElement *hovered =
3665 Environment->getRootGUIElement()->getElementFromPoint(
3666 core::position2d<s32>(x, y));
3667 if (hovered && isMyChild(hovered) &&
3668 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3669 gui::IGUISkin* skin = Environment->getSkin();
3670 sanity_check(skin != NULL);
3671 gui::IGUIFont *old_font = skin->getFont();
3672 skin->setFont(m_font);
3673 bool retval = hovered->OnEvent(event);
3674 skin->setFont(old_font);
3679 // Fix Esc/Return key being eaten by checkboxen and tables
3680 if(event.EventType==EET_KEY_INPUT_EVENT) {
3681 KeyPress kp(event.KeyInput);
3682 if (kp == EscapeKey || kp == CancelKey
3683 || kp == getKeySetting("keymap_inventory")
3684 || event.KeyInput.Key==KEY_RETURN) {
3685 gui::IGUIElement *focused = Environment->getFocus();
3686 if (focused && isMyChild(focused) &&
3687 (focused->getType() == gui::EGUIET_LIST_BOX ||
3688 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3689 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3690 event.KeyInput.Key != KEY_RETURN)) {
3696 // Mouse wheel and move events: send to hovered element instead of focused
3697 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3698 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3699 event.MouseInput.Event == EMIE_MOUSE_MOVED)) {
3700 s32 x = event.MouseInput.X;
3701 s32 y = event.MouseInput.Y;
3702 gui::IGUIElement *hovered =
3703 Environment->getRootGUIElement()->getElementFromPoint(
3704 core::position2d<s32>(x, y));
3705 if (hovered && isMyChild(hovered)) {
3706 hovered->OnEvent(event);
3707 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3711 if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3712 s32 x = event.MouseInput.X;
3713 s32 y = event.MouseInput.Y;
3714 gui::IGUIElement *hovered =
3715 Environment->getRootGUIElement()->getElementFromPoint(
3716 core::position2d<s32>(x, y));
3717 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3718 m_old_tooltip_id = -1;
3720 if (!isChild(hovered,this)) {
3721 if (DoubleClickDetection(event)) {
3727 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3728 /* TODO add a check like:
3729 if (event.JoystickEvent != joystick_we_listen_for)
3732 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3734 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3736 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3738 acceptInput(quit_mode_accept);
3746 return GUIModalMenu::preprocessEvent(event);
3749 /******************************************************************************/
3750 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3752 /* The following code is for capturing double-clicks of the mouse button
3753 * and translating the double-click into an EET_KEY_INPUT_EVENT event
3754 * -- which closes the form -- under some circumstances.
3756 * There have been many github issues reporting this as a bug even though it
3757 * was an intended feature. For this reason, remapping the double-click as
3758 * an ESC must be explicitly set when creating this class via the
3759 * /p remap_dbl_click parameter of the constructor.
3762 if (!m_remap_dbl_click)
3765 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3766 m_doubleclickdetect[0].pos = m_doubleclickdetect[1].pos;
3767 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3769 m_doubleclickdetect[1].pos = m_pointer;
3770 m_doubleclickdetect[1].time = porting::getTimeMs();
3772 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3773 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3778 double squaredistance =
3779 m_doubleclickdetect[0].pos
3780 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3782 if (squaredistance > (30*30)) {
3786 SEvent* translated = new SEvent();
3787 assert(translated != 0);
3788 //translate doubleclick to escape
3789 memset(translated, 0, sizeof(SEvent));
3790 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3791 translated->KeyInput.Key = KEY_ESCAPE;
3792 translated->KeyInput.Control = false;
3793 translated->KeyInput.Shift = false;
3794 translated->KeyInput.PressedDown = true;
3795 translated->KeyInput.Char = 0;
3796 OnEvent(*translated);
3798 // no need to send the key up event as we're already deleted
3799 // and no one else did notice this event
3807 void GUIFormSpecMenu::tryClose()
3811 acceptInput(quit_mode_cancel);
3814 m_text_dst->gotText(L"MenuQuit");
3818 enum ButtonEventType : u8
3831 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3833 if (event.EventType==EET_KEY_INPUT_EVENT) {
3834 KeyPress kp(event.KeyInput);
3835 if (event.KeyInput.PressedDown && (
3836 (kp == EscapeKey) || (kp == CancelKey) ||
3837 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3842 if (m_client != NULL && event.KeyInput.PressedDown &&
3843 (kp == getKeySetting("keymap_screenshot"))) {
3844 m_client->makeScreenshot();
3846 if (event.KeyInput.PressedDown &&
3847 (event.KeyInput.Key==KEY_RETURN ||
3848 event.KeyInput.Key==KEY_UP ||
3849 event.KeyInput.Key==KEY_DOWN)
3851 switch (event.KeyInput.Key) {
3853 current_keys_pending.key_enter = true;
3856 current_keys_pending.key_up = true;
3859 current_keys_pending.key_down = true;
3863 //can't happen at all!
3864 FATAL_ERROR("Reached a source line that can't ever been reached");
3867 if (current_keys_pending.key_enter && m_allowclose) {
3868 acceptInput(quit_mode_accept);
3878 /* Mouse event other than movement, or crossing the border of inventory
3879 field while holding right mouse button
3881 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3882 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3883 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3884 event.MouseInput.isRightPressed() &&
3885 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3887 // Get selected item and hovered/clicked item (s)
3889 m_old_tooltip_id = -1;
3890 updateSelectedItem();
3891 ItemSpec s = getItemAtPos(m_pointer);
3893 Inventory *inv_selected = NULL;
3894 Inventory *inv_s = NULL;
3895 InventoryList *list_s = NULL;
3897 if (m_selected_item) {
3898 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3899 sanity_check(inv_selected);
3900 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3907 inv_s = m_invmgr->getInventory(s.inventoryloc);
3910 errorstream << "InventoryMenu: The selected inventory location "
3911 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3913 s.i = -1; // make it invalid again
3917 list_s = inv_s->getList(s.listname);
3918 if (list_s == NULL) {
3919 verbosestream << "InventoryMenu: The selected inventory list \""
3920 << s.listname << "\" does not exist" << std::endl;
3921 s.i = -1; // make it invalid again
3925 if ((u32)s.i >= list_s->getSize()) {
3926 infostream << "InventoryMenu: The selected inventory list \""
3927 << s.listname << "\" is too small (i=" << s.i << ", size="
3928 << list_s->getSize() << ")" << std::endl;
3929 s.i = -1; // make it invalid again
3933 s_count = list_s->getItem(s.i).count;
3936 bool identical = m_selected_item && s.isValid() &&
3937 (inv_selected == inv_s) &&
3938 (m_selected_item->listname == s.listname) &&
3939 (m_selected_item->i == s.i);
3941 ButtonEventType button = BET_LEFT;
3942 ButtonEventType updown = BET_OTHER;
3943 switch (event.MouseInput.Event) {
3944 case EMIE_LMOUSE_PRESSED_DOWN:
3945 button = BET_LEFT; updown = BET_DOWN;
3947 case EMIE_RMOUSE_PRESSED_DOWN:
3948 button = BET_RIGHT; updown = BET_DOWN;
3950 case EMIE_MMOUSE_PRESSED_DOWN:
3951 button = BET_MIDDLE; updown = BET_DOWN;
3953 case EMIE_MOUSE_WHEEL:
3954 button = (event.MouseInput.Wheel > 0) ?
3955 BET_WHEEL_UP : BET_WHEEL_DOWN;
3958 case EMIE_LMOUSE_LEFT_UP:
3959 button = BET_LEFT; updown = BET_UP;
3961 case EMIE_RMOUSE_LEFT_UP:
3962 button = BET_RIGHT; updown = BET_UP;
3964 case EMIE_MMOUSE_LEFT_UP:
3965 button = BET_MIDDLE; updown = BET_UP;
3967 case EMIE_MOUSE_MOVED:
3974 // Set this number to a positive value to generate a move action
3975 // from m_selected_item to s.
3976 u32 move_amount = 0;
3978 // Set this number to a positive value to generate a move action
3979 // from s to the next inventory ring.
3980 u32 shift_move_amount = 0;
3982 // Set this number to a positive value to generate a drop action
3983 // from m_selected_item.
3984 u32 drop_amount = 0;
3986 // Set this number to a positive value to generate a craft action at s.
3987 u32 craft_amount = 0;
3991 // Some mouse button has been pressed
3993 //infostream<<"Mouse button "<<button<<" pressed at p=("
3994 // <<p.X<<","<<p.Y<<")"<<std::endl;
3996 m_selected_dragging = false;
3998 if (s.isValid() && s.listname == "craftpreview") {
3999 // Craft preview has been clicked: craft
4000 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4001 } else if (!m_selected_item) {
4002 if (s_count && button != BET_WHEEL_UP) {
4003 // Non-empty stack has been clicked: select or shift-move it
4004 m_selected_item = new ItemSpec(s);
4007 if (button == BET_RIGHT)
4008 count = (s_count + 1) / 2;
4009 else if (button == BET_MIDDLE)
4010 count = MYMIN(s_count, 10);
4011 else if (button == BET_WHEEL_DOWN)
4016 if (!event.MouseInput.Shift) {
4017 // no shift: select item
4018 m_selected_amount = count;
4019 m_selected_dragging = button != BET_WHEEL_DOWN;
4020 m_auto_place = false;
4022 // shift pressed: move item, right click moves 1
4023 shift_move_amount = button == BET_RIGHT ? 1 : count;
4026 } else { // m_selected_item != NULL
4027 assert(m_selected_amount >= 1);
4030 // Clicked a slot: move
4031 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4033 else if (button == BET_MIDDLE)
4034 move_amount = MYMIN(m_selected_amount, 10);
4035 else if (button == BET_LEFT)
4036 move_amount = m_selected_amount;
4040 if (button == BET_WHEEL_DOWN) {
4041 if (m_selected_amount < s_count)
4042 ++m_selected_amount;
4044 if (move_amount >= m_selected_amount)
4045 m_selected_amount = 0;
4047 m_selected_amount -= move_amount;
4051 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4052 && button != BET_WHEEL_DOWN) {
4053 // Clicked outside of the window: drop
4054 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4056 else if (button == BET_MIDDLE)
4057 drop_amount = MYMIN(m_selected_amount, 10);
4059 drop_amount = m_selected_amount;
4064 // Some mouse button has been released
4066 //infostream<<"Mouse button "<<button<<" released at p=("
4067 // <<p.X<<","<<p.Y<<")"<<std::endl;
4069 if (m_selected_dragging && m_selected_item) {
4072 // Dragged to different slot: move all selected
4073 move_amount = m_selected_amount;
4075 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4076 // Dragged outside of window: drop all selected
4077 drop_amount = m_selected_amount;
4081 m_selected_dragging = false;
4082 // Keep track of whether the mouse button be released
4083 // One click is drag without dropping. Click + release
4084 // + click changes to drop item when moved mode
4085 if (m_selected_item)
4086 m_auto_place = true;
4089 // Mouse has been moved and rmb is down and mouse pointer just
4090 // entered a new inventory field (checked in the entry-if, this
4091 // is the only action here that is generated by mouse movement)
4092 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4094 // TODO: middle mouse to move 10 items might be handy
4096 // Only move an item if the destination slot is empty
4097 // or contains the same item type as what is going to be
4099 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4100 InventoryList *list_to = list_s;
4101 assert(list_from && list_to);
4102 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4103 ItemStack stack_to = list_to->getItem(s.i);
4104 if (stack_to.empty() || stack_to.name == stack_from.name)
4113 // Possibly send inventory action to server
4114 if (move_amount > 0) {
4115 // Send IAction::Move
4117 assert(m_selected_item && m_selected_item->isValid());
4118 assert(s.isValid());
4120 assert(inv_selected && inv_s);
4121 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4122 InventoryList *list_to = list_s;
4123 assert(list_from && list_to);
4124 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4125 ItemStack stack_to = list_to->getItem(s.i);
4127 // Check how many items can be moved
4128 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4129 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4131 // If source stack cannot be added to destination stack at all,
4133 if (leftover.count == stack_from.count &&
4134 leftover.name == stack_from.name) {
4136 if (m_selected_swap.empty()) {
4137 m_selected_amount = stack_to.count;
4138 m_selected_dragging = false;
4140 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4141 // Skip next validation checks due async inventory calls
4142 m_selected_swap = stack_to;
4147 // Source stack goes fully into destination stack
4148 else if (leftover.empty()) {
4149 m_selected_amount -= move_amount;
4151 // Source stack goes partly into destination stack
4153 move_amount -= leftover.count;
4154 m_selected_amount -= move_amount;
4158 infostream << "Handing IAction::Move to manager" << std::endl;
4159 IMoveAction *a = new IMoveAction();
4160 a->count = move_amount;
4161 a->from_inv = m_selected_item->inventoryloc;
4162 a->from_list = m_selected_item->listname;
4163 a->from_i = m_selected_item->i;
4164 a->to_inv = s.inventoryloc;
4165 a->to_list = s.listname;
4167 m_invmgr->inventoryAction(a);
4169 } else if (shift_move_amount > 0) {
4170 u32 mis = m_inventory_rings.size();
4172 for (; i < mis; i++) {
4173 const ListRingSpec &sp = m_inventory_rings[i];
4174 if (sp.inventoryloc == s.inventoryloc
4175 && sp.listname == s.listname)
4179 if (i >= mis) // if not found
4181 u32 to_inv_ind = (i + 1) % mis;
4182 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4183 InventoryList *list_from = list_s;
4186 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4189 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4192 ItemStack stack_from = list_from->getItem(s.i);
4193 assert(shift_move_amount <= stack_from.count);
4195 infostream << "Handing IAction::Move to manager" << std::endl;
4196 IMoveAction *a = new IMoveAction();
4197 a->count = shift_move_amount;
4198 a->from_inv = s.inventoryloc;
4199 a->from_list = s.listname;
4201 a->to_inv = to_inv_sp.inventoryloc;
4202 a->to_list = to_inv_sp.listname;
4203 a->move_somewhere = true;
4204 m_invmgr->inventoryAction(a);
4206 } else if (drop_amount > 0) {
4207 // Send IAction::Drop
4209 assert(m_selected_item && m_selected_item->isValid());
4210 assert(inv_selected);
4211 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4213 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4215 // Check how many items can be dropped
4216 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4217 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4218 m_selected_amount -= drop_amount;
4220 infostream << "Handing IAction::Drop to manager" << std::endl;
4221 IDropAction *a = new IDropAction();
4222 a->count = drop_amount;
4223 a->from_inv = m_selected_item->inventoryloc;
4224 a->from_list = m_selected_item->listname;
4225 a->from_i = m_selected_item->i;
4226 m_invmgr->inventoryAction(a);
4227 } else if (craft_amount > 0) {
4228 assert(s.isValid());
4230 // if there are no items selected or the selected item
4231 // belongs to craftresult list, proceed with crafting
4232 if (m_selected_item == NULL ||
4233 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4237 // Send IACTION_CRAFT
4238 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4239 ICraftAction *a = new ICraftAction();
4240 a->count = craft_amount;
4241 a->craft_inv = s.inventoryloc;
4242 m_invmgr->inventoryAction(a);
4246 // If m_selected_amount has been decreased to zero, deselect
4247 if (m_selected_amount == 0) {
4248 m_selected_swap.clear();
4249 delete m_selected_item;
4250 m_selected_item = NULL;
4251 m_selected_amount = 0;
4252 m_selected_dragging = false;
4254 m_old_pointer = m_pointer;
4257 if (event.EventType == EET_GUI_EVENT) {
4258 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4260 // find the element that was clicked
4261 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4262 if ((s.ftype == f_TabHeader) &&
4263 (s.fid == event.GUIEvent.Caller->getID())) {
4271 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4273 if (!canTakeFocus(event.GUIEvent.Element)) {
4274 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4276 // Returning true disables focus change
4280 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4281 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4282 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4283 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4284 unsigned int btn_id = event.GUIEvent.Caller->getID();
4286 if (btn_id == 257) {
4288 acceptInput(quit_mode_accept);
4292 m_text_dst->gotText(L"ExitButton");
4294 // quitMenu deallocates menu
4298 // find the element that was clicked
4299 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4300 // if its a button, set the send field so
4301 // lua knows which button was pressed
4302 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
4303 s.fid == event.GUIEvent.Caller->getID()) {
4307 acceptInput(quit_mode_accept);
4310 m_text_dst->gotText(L"ExitButton");
4315 acceptInput(quit_mode_no);
4319 } else if ((s.ftype == f_DropDown) &&
4320 (s.fid == event.GUIEvent.Caller->getID())) {
4321 // only send the changed dropdown
4322 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4323 if (s2.ftype == f_DropDown) {
4328 acceptInput(quit_mode_no);
4330 // revert configuration to make sure dropdowns are sent on
4331 // regular button click
4332 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4333 if (s2.ftype == f_DropDown) {
4338 } else if ((s.ftype == f_ScrollBar) &&
4339 (s.fid == event.GUIEvent.Caller->getID())) {
4340 s.fdefault = L"Changed";
4341 acceptInput(quit_mode_no);
4343 } else if ((s.ftype == f_Unknown) &&
4344 (s.fid == event.GUIEvent.Caller->getID())) {
4352 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4353 if (event.GUIEvent.Caller->getID() > 257) {
4354 bool close_on_enter = true;
4355 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4356 if (s.ftype == f_Unknown &&
4357 s.fid == event.GUIEvent.Caller->getID()) {
4358 current_field_enter_pending = s.fname;
4359 std::unordered_map<std::string, bool>::const_iterator it =
4360 field_close_on_enter.find(s.fname);
4361 if (it != field_close_on_enter.end())
4362 close_on_enter = (*it).second;
4368 if (m_allowclose && close_on_enter) {
4369 current_keys_pending.key_enter = true;
4370 acceptInput(quit_mode_accept);
4373 current_keys_pending.key_enter = true;
4376 // quitMenu deallocates menu
4381 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4382 int current_id = event.GUIEvent.Caller->getID();
4383 if (current_id > 257) {
4384 // find the element that was clicked
4385 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4386 // if it's a table, set the send field
4387 // so lua knows which table was changed
4388 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4399 return Parent ? Parent->OnEvent(event) : false;
4403 * get name of element by element id
4404 * @param id of element
4405 * @return name string or empty string
4407 std::string GUIFormSpecMenu::getNameByID(s32 id)
4409 for (FieldSpec &spec : m_fields) {
4417 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4419 for (FieldSpec &spec : m_fields) {
4427 * get label of element by id
4428 * @param id of element
4429 * @return label string or empty string
4431 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4433 for (FieldSpec &spec : m_fields) {
4440 StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
4441 const std::string &name, const std::string &parent_type) {
4444 if (!parent_type.empty()) {
4445 auto it = theme_by_type.find(parent_type);
4446 if (it != theme_by_type.end()) {
4451 auto it = theme_by_type.find(type);
4452 if (it != theme_by_type.end()) {
4456 it = theme_by_name.find(name);
4457 if (it != theme_by_name.end()) {