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 "constants.h"
29 #include "client/keycode.h"
30 #include "util/strfnd.h"
31 #include <IGUIButton.h>
32 #include <IGUICheckBox.h>
33 #include <IGUIComboBox.h>
34 #include <IGUIEditBox.h>
35 #include <IGUIStaticText.h>
37 #include <IGUITabControl.h>
38 #include "client/renderingengine.h"
40 #include "client/tile.h" // ITextureSource
41 #include "client/hud.h" // drawItemStack
45 #include "scripting_server.h"
46 #include "mainmenumanager.h"
49 #include "client/client.h"
50 #include "client/fontengine.h"
52 #include "util/numeric.h"
53 #include "util/string.h" // for parseColorString()
54 #include "irrlicht_changes/static_text.h"
55 #include "client/guiscalingfilter.h"
56 #include "guiAnimatedImage.h"
57 #include "guiBackgroundImage.h"
59 #include "guiButton.h"
60 #include "guiButtonImage.h"
61 #include "guiButtonItemImage.h"
62 #include "guiEditBoxWithScrollbar.h"
63 #include "guiInventoryList.h"
64 #include "guiItemImage.h"
65 #include "guiScrollContainer.h"
66 #include "intlGUIEditBox.h"
67 #include "guiHyperText.h"
69 #define MY_CHECKPOS(a,b) \
70 if (v_pos.size() != 2) { \
71 errorstream<< "Invalid pos for element " << a << "specified: \"" \
72 << parts[b] << "\"" << std::endl; \
76 #define MY_CHECKGEOM(a,b) \
77 if (v_geom.size() != 2) { \
78 errorstream<< "Invalid geometry for element " << a << \
79 "specified: \"" << parts[b] << "\"" << std::endl; \
85 static unsigned int font_line_height(gui::IGUIFont *font)
87 return font->getDimension(L"Ay").Height + font->getKerningHeight();
90 inline u32 clamp_u8(s32 value)
92 return (u32) MYMIN(MYMAX(value, 0), 255);
95 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
96 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
97 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
98 const std::string &formspecPrepend, bool remap_dbl_click):
99 GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr, remap_dbl_click),
103 m_formspec_prepend(formspecPrepend),
108 current_keys_pending.key_down = false;
109 current_keys_pending.key_up = false;
110 current_keys_pending.key_enter = false;
111 current_keys_pending.key_escape = false;
113 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
114 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
117 GUIFormSpecMenu::~GUIFormSpecMenu()
121 for (auto &table_it : m_tables)
122 table_it.second->drop();
123 for (auto &inventorylist_it : m_inventorylists)
124 inventorylist_it->drop();
125 for (auto &checkbox_it : m_checkboxes)
126 checkbox_it.second->drop();
127 for (auto &scrollbar_it : m_scrollbars)
128 scrollbar_it.second->drop();
129 for (auto &background_it : m_backgrounds)
130 background_it->drop();
131 for (auto &tooltip_rect_it : m_tooltip_rects)
132 tooltip_rect_it.first->drop();
133 for (auto &clickthrough_it : m_clickthrough_elements)
134 clickthrough_it->drop();
135 for (auto &scroll_container_it : m_scroll_containers)
136 scroll_container_it.second->drop();
138 delete m_selected_item;
143 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
144 JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
145 const std::string &formspecPrepend)
147 if (cur_formspec == nullptr) {
148 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
149 client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
150 cur_formspec->doPause = false;
153 Caution: do not call (*cur_formspec)->drop() here --
154 the reference might outlive the menu, so we will
155 periodically check if *cur_formspec is the only
156 remaining reference (i.e. the menu was removed)
157 and delete it in that case.
161 cur_formspec->setFormspecPrepend(formspecPrepend);
162 cur_formspec->setFormSource(fs_src);
163 cur_formspec->setTextDest(txt_dest);
167 void GUIFormSpecMenu::removeChildren()
169 const core::list<gui::IGUIElement*> &children = getChildren();
171 while (!children.empty()) {
172 (*children.getLast())->remove();
175 if (m_tooltip_element) {
176 m_tooltip_element->remove();
177 m_tooltip_element->drop();
178 m_tooltip_element = nullptr;
182 void GUIFormSpecMenu::setInitialFocus()
184 // Set initial focus according to following order of precedence:
185 // 1. first empty editbox
189 // 5. first focusable (not statictext, not tabheader)
190 // 6. first child element
192 core::list<gui::IGUIElement*> children = getChildren();
194 // in case "children" contains any NULL elements, remove them
195 for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
196 it != children.end();) {
200 it = children.erase(it);
203 // 1. first empty editbox
204 for (gui::IGUIElement *it : children) {
205 if (it->getType() == gui::EGUIET_EDIT_BOX
206 && it->getText()[0] == 0) {
207 Environment->setFocus(it);
213 for (gui::IGUIElement *it : children) {
214 if (it->getType() == gui::EGUIET_EDIT_BOX) {
215 Environment->setFocus(it);
221 for (gui::IGUIElement *it : children) {
222 if (it->getTypeName() == std::string("GUITable")) {
223 Environment->setFocus(it);
229 for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
230 it != children.end(); --it) {
231 if ((*it)->getType() == gui::EGUIET_BUTTON) {
232 Environment->setFocus(*it);
237 // 5. first focusable (not statictext, not tabheader)
238 for (gui::IGUIElement *it : children) {
239 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
240 it->getType() != gui::EGUIET_TAB_CONTROL) {
241 Environment->setFocus(it);
246 // 6. first child element
247 if (children.empty())
248 Environment->setFocus(this);
250 Environment->setFocus(*(children.begin()));
253 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
255 for (auto &table : m_tables) {
256 if (tablename == table.first.fname)
262 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
264 for (auto &dropdown : m_dropdowns) {
265 if (name == dropdown.first.fname)
266 return &dropdown.second;
271 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
273 v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
275 pos_f.X += stof((*v_pos)[0]) * spacing.X;
276 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
278 return v2s32(pos_f.X, pos_f.Y);
281 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
283 return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
284 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
287 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
289 return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
292 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
294 std::vector<std::string> parts = split(element,',');
296 if (((parts.size() == 2) || parts.size() == 3) ||
297 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
299 if (parts[1].find(';') != std::string::npos)
300 parts[1] = parts[1].substr(0,parts[1].find(';'));
302 data->invsize.X = MYMAX(0, stof(parts[0]));
303 data->invsize.Y = MYMAX(0, stof(parts[1]));
307 if (parts.size() == 3) {
308 if (parts[2] == "true") {
309 lockSize(true,v2u32(800,600));
313 data->explicit_size = true;
316 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
319 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
321 std::vector<std::string> parts = split(element, ',');
323 if (parts.size() >= 2) {
324 if (parts[1].find(';') != std::string::npos)
325 parts[1] = parts[1].substr(0, parts[1].find(';'));
327 container_stack.push(pos_offset);
328 pos_offset.X += stof(parts[0]);
329 pos_offset.Y += stof(parts[1]);
332 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
335 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
337 if (container_stack.empty()) {
338 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
340 pos_offset = container_stack.top();
341 container_stack.pop();
345 void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
347 std::vector<std::string> parts = split(element, ';');
349 if (parts.size() < 4 ||
350 (parts.size() > 5 && m_formspec_version <= FORMSPEC_API_VERSION)) {
351 errorstream << "Invalid scroll_container start element (" << parts.size()
352 << "): '" << element << "'" << std::endl;
356 std::vector<std::string> v_pos = split(parts[0], ',');
357 std::vector<std::string> v_geom = split(parts[1], ',');
358 std::string scrollbar_name = parts[2];
359 std::string orientation = parts[3];
360 f32 scroll_factor = 0.1f;
361 if (parts.size() >= 5 && !parts[4].empty())
362 scroll_factor = stof(parts[4]);
364 MY_CHECKPOS("scroll_container", 0);
365 MY_CHECKGEOM("scroll_container", 1);
367 v2s32 pos = getRealCoordinateBasePos(v_pos);
368 v2s32 geom = getRealCoordinateGeometry(v_geom);
370 if (orientation == "vertical")
371 scroll_factor *= -imgsize.Y;
372 else if (orientation == "horizontal")
373 scroll_factor *= -imgsize.X;
375 warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
376 << "Invalid scroll_container orientation: " << orientation
379 // old parent (at first: this)
380 // ^ is parent of clipper
381 // ^ is parent of mover
382 // ^ is parent of other elements
385 core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
387 gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
388 data->current_parent, 0, rect_clipper);
391 FieldSpec spec_mover(
395 258 + m_fields.size()
398 core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
400 GUIScrollContainer *mover = new GUIScrollContainer(Environment,
401 clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
403 data->current_parent = mover;
405 m_scroll_containers.emplace_back(scrollbar_name, mover);
407 m_fields.push_back(spec_mover);
411 // remove interferring offset of normal containers
412 container_stack.push(pos_offset);
417 void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
419 if (data->current_parent == this || data->current_parent->getParent() == this ||
420 container_stack.empty()) {
421 errorstream << "Invalid scroll_container end element, "
422 << "no matching scroll_container start element" << std::endl;
426 if (pos_offset.getLengthSQ() != 0.0f) {
427 // pos_offset is only set by containers and scroll_containers.
428 // scroll_containers always set it to 0,0 which means that if it is
429 // not 0,0, it is a normal container that was opened last, not a
431 errorstream << "Invalid scroll_container end element, "
432 << "an inner container was left open" << std::endl;
436 data->current_parent = data->current_parent->getParent()->getParent();
437 pos_offset = container_stack.top();
438 container_stack.pop();
441 void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
444 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
448 std::vector<std::string> parts = split(element,';');
450 if (((parts.size() == 4) || (parts.size() == 5)) ||
451 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
453 std::string location = parts[0];
454 std::string listname = parts[1];
455 std::vector<std::string> v_pos = split(parts[2],',');
456 std::vector<std::string> v_geom = split(parts[3],',');
457 std::string startindex;
458 if (parts.size() == 5)
459 startindex = parts[4];
461 MY_CHECKPOS("list",2);
462 MY_CHECKGEOM("list",3);
464 InventoryLocation loc;
466 if (location == "context" || location == "current_name")
467 loc = m_current_inventory_location;
469 loc.deSerialize(location);
472 geom.X = stoi(v_geom[0]);
473 geom.Y = stoi(v_geom[1]);
476 if (!startindex.empty())
477 start_i = stoi(startindex);
479 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
480 errorstream << "Invalid list element: '" << element << "'" << std::endl;
484 if (!data->explicit_size)
485 warningstream << "invalid use of list without a size[] element" << std::endl;
491 258 + m_fields.size(),
495 v2f32 slot_spacing = data->real_coordinates ?
496 v2f32(imgsize.X * 1.25f, imgsize.Y * 1.25f) : spacing;
498 v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos)
499 : getElementBasePos(&v_pos);
501 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
502 pos.X + (geom.X - 1) * slot_spacing.X + imgsize.X,
503 pos.Y + (geom.Y - 1) * slot_spacing.Y + imgsize.Y);
505 GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
506 spec.fid, rect, m_invmgr, loc, listname, geom, start_i, imgsize,
507 slot_spacing, this, data->inventorylist_options, m_font);
509 m_inventorylists.push_back(e);
510 m_fields.push_back(spec);
513 errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl;
516 void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
519 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
523 std::vector<std::string> parts = split(element, ';');
525 if (parts.size() == 2) {
526 std::string location = parts[0];
527 std::string listname = parts[1];
529 InventoryLocation loc;
531 if (location == "context" || location == "current_name")
532 loc = m_current_inventory_location;
534 loc.deSerialize(location);
536 m_inventory_rings.emplace_back(loc, listname);
540 if (element.empty() && m_inventorylists.size() > 1) {
541 size_t siz = m_inventorylists.size();
542 // insert the last two inv list elements into the list ring
543 const GUIInventoryList *spa = m_inventorylists[siz - 2];
544 const GUIInventoryList *spb = m_inventorylists[siz - 1];
545 m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname());
546 m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname());
550 errorstream<< "Invalid list ring element(" << parts.size() << ", "
551 << m_inventorylists.size() << "): '" << element << "'" << std::endl;
554 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
556 std::vector<std::string> parts = split(element,';');
558 if (((parts.size() >= 3) && (parts.size() <= 4)) ||
559 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
561 std::vector<std::string> v_pos = split(parts[0],',');
562 std::string name = parts[1];
563 std::string label = parts[2];
564 std::string selected;
566 if (parts.size() >= 4)
569 MY_CHECKPOS("checkbox",0);
571 bool fselected = false;
573 if (selected == "true")
576 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
577 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
578 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
579 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
582 core::rect<s32> rect;
584 if (data->real_coordinates) {
585 pos = getRealCoordinateBasePos(v_pos);
587 rect = core::rect<s32>(
590 pos.X + label_size.Width + cb_size + 7,
594 pos = getElementBasePos(&v_pos);
595 rect = core::rect<s32>(
597 pos.Y + imgsize.Y / 2 - y_center,
598 pos.X + label_size.Width + cb_size + 7,
599 pos.Y + imgsize.Y / 2 + y_center
605 wlabel, //Needed for displaying text on MSVC
610 spec.ftype = f_CheckBox;
612 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
613 data->current_parent, spec.fid, spec.flabel.c_str());
615 auto style = getDefaultStyleForElement("checkbox", name);
616 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
618 if (spec.fname == m_focused_element) {
619 Environment->setFocus(e);
623 m_checkboxes.emplace_back(spec, e);
624 m_fields.push_back(spec);
627 errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl;
630 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
632 std::vector<std::string> parts = split(element,';');
634 if (parts.size() >= 5) {
635 std::vector<std::string> v_pos = split(parts[0],',');
636 std::vector<std::string> v_geom = split(parts[1],',');
637 std::string name = parts[3];
638 std::string value = parts[4];
640 MY_CHECKPOS("scrollbar",0);
641 MY_CHECKGEOM("scrollbar",1);
646 if (data->real_coordinates) {
647 pos = getRealCoordinateBasePos(v_pos);
648 dim = getRealCoordinateGeometry(v_geom);
650 pos = getElementBasePos(&v_pos);
651 dim.X = stof(v_geom[0]) * spacing.X;
652 dim.Y = stof(v_geom[1]) * spacing.Y;
655 core::rect<s32> rect =
656 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
665 bool is_horizontal = true;
667 if (parts[2] == "vertical")
668 is_horizontal = false;
670 spec.ftype = f_ScrollBar;
672 GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent,
673 spec.fid, rect, is_horizontal, true);
675 auto style = getDefaultStyleForElement("scrollbar", name);
676 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
677 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
679 s32 max = data->scrollbar_options.max;
680 s32 min = data->scrollbar_options.min;
685 e->setPos(stoi(parts[4]));
687 e->setSmallStep(data->scrollbar_options.small_step);
688 e->setLargeStep(data->scrollbar_options.large_step);
690 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
692 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
694 if (spec.fname == m_focused_element) {
695 Environment->setFocus(e);
698 m_scrollbars.emplace_back(spec,e);
699 m_fields.push_back(spec);
702 errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element
706 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
708 std::vector<std::string> parts = split(element, ';');
710 if (parts.size() == 0) {
711 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
712 element << "'" << std::endl;
716 for (const std::string &i : parts) {
717 std::vector<std::string> options = split(i, '=');
719 if (options.size() != 2) {
720 warningstream << "Invalid scrollbaroptions option syntax: '" <<
721 element << "'" << std::endl;
722 continue; // Go to next option
725 if (options[0] == "max") {
726 data->scrollbar_options.max = stoi(options[1]);
728 } else if (options[0] == "min") {
729 data->scrollbar_options.min = stoi(options[1]);
731 } else if (options[0] == "smallstep") {
732 int value = stoi(options[1]);
733 data->scrollbar_options.small_step = value < 0 ? 10 : value;
735 } else if (options[0] == "largestep") {
736 int value = stoi(options[1]);
737 data->scrollbar_options.large_step = value < 0 ? 100 : value;
739 } else if (options[0] == "thumbsize") {
740 int value = stoi(options[1]);
741 data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
743 } else if (options[0] == "arrows") {
744 std::string value = trim(options[1]);
746 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
747 else if (value == "show")
748 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
749 else // Auto hide/show
750 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
754 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
755 "): '" << element << "'" << std::endl;
759 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
761 std::vector<std::string> parts = split(element,';');
763 if ((parts.size() == 3) ||
764 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
766 std::vector<std::string> v_pos = split(parts[0],',');
767 std::vector<std::string> v_geom = split(parts[1],',');
768 std::string name = unescape_string(parts[2]);
770 MY_CHECKPOS("image", 0);
771 MY_CHECKGEOM("image", 1);
776 if (data->real_coordinates) {
777 pos = getRealCoordinateBasePos(v_pos);
778 geom = getRealCoordinateGeometry(v_geom);
780 pos = getElementBasePos(&v_pos);
781 geom.X = stof(v_geom[0]) * (float)imgsize.X;
782 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
785 if (!data->explicit_size)
786 warningstream<<"invalid use of image without a size[] element"<<std::endl;
788 video::ITexture *texture = m_tsrc->getTexture(name);
790 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
791 << std::endl << "\t" << name << std::endl;
799 258 + m_fields.size(),
802 core::rect<s32> rect(pos, pos + geom);
803 gui::IGUIImage *e = Environment->addImage(rect, data->current_parent,
805 e->setImage(texture);
806 e->setScaleImage(true);
807 auto style = getDefaultStyleForElement("image", spec.fname);
808 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
809 m_fields.push_back(spec);
811 // images should let events through
813 m_clickthrough_elements.push_back(e);
817 if (parts.size() == 2) {
818 std::vector<std::string> v_pos = split(parts[0],',');
819 std::string name = unescape_string(parts[1]);
821 MY_CHECKPOS("image", 0);
823 v2s32 pos = getElementBasePos(&v_pos);
825 if (!data->explicit_size)
826 warningstream<<"invalid use of image without a size[] element"<<std::endl;
828 video::ITexture *texture = m_tsrc->getTexture(name);
830 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
831 << std::endl << "\t" << name << std::endl;
839 258 + m_fields.size()
841 gui::IGUIImage *e = Environment->addImage(texture, pos, true,
842 data->current_parent, spec.fid, 0);
843 auto style = getDefaultStyleForElement("image", spec.fname);
844 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
845 m_fields.push_back(spec);
847 // images should let events through
849 m_clickthrough_elements.push_back(e);
852 errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl;
855 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
857 std::vector<std::string> parts = split(element, ';');
859 if (parts.size() != 6 && parts.size() != 7 &&
860 !(parts.size() > 7 && m_formspec_version > FORMSPEC_API_VERSION)) {
861 errorstream << "Invalid animated_image element(" << parts.size()
862 << "): '" << element << "'" << std::endl;
866 std::vector<std::string> v_pos = split(parts[0], ',');
867 std::vector<std::string> v_geom = split(parts[1], ',');
868 std::string name = parts[2];
869 std::string texture_name = unescape_string(parts[3]);
870 s32 frame_count = stoi(parts[4]);
871 s32 frame_duration = stoi(parts[5]);
873 MY_CHECKPOS("animated_image", 0);
874 MY_CHECKGEOM("animated_image", 1);
879 if (data->real_coordinates) {
880 pos = getRealCoordinateBasePos(v_pos);
881 geom = getRealCoordinateGeometry(v_geom);
883 pos = getElementBasePos(&v_pos);
884 geom.X = stof(v_geom[0]) * (float)imgsize.X;
885 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
888 if (!data->explicit_size)
889 warningstream << "Invalid use of animated_image without a size[] element" << std::endl;
895 258 + m_fields.size()
897 spec.ftype = f_AnimatedImage;
900 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
902 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid,
903 rect, texture_name, frame_count, frame_duration, m_tsrc);
905 if (parts.size() >= 7)
906 e->setFrameIndex(stoi(parts[6]) - 1);
908 auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
909 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
911 // Animated images should let events through
912 m_clickthrough_elements.push_back(e);
914 m_fields.push_back(spec);
917 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
919 std::vector<std::string> parts = split(element,';');
921 if ((parts.size() == 3) ||
922 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
924 std::vector<std::string> v_pos = split(parts[0],',');
925 std::vector<std::string> v_geom = split(parts[1],',');
926 std::string name = parts[2];
928 MY_CHECKPOS("itemimage",0);
929 MY_CHECKGEOM("itemimage",1);
934 if (data->real_coordinates) {
935 pos = getRealCoordinateBasePos(v_pos);
936 geom = getRealCoordinateGeometry(v_geom);
938 pos = getElementBasePos(&v_pos);
939 geom.X = stof(v_geom[0]) * (float)imgsize.X;
940 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
943 if(!data->explicit_size)
944 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
950 258 + m_fields.size(),
953 spec.ftype = f_ItemImage;
955 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
956 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
957 auto style = getDefaultStyleForElement("item_image", spec.fname);
958 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
960 // item images should let events through
961 m_clickthrough_elements.push_back(e);
963 m_fields.push_back(spec);
966 errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
969 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
970 const std::string &type)
972 std::vector<std::string> parts = split(element,';');
974 if ((parts.size() == 4) ||
975 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
977 std::vector<std::string> v_pos = split(parts[0],',');
978 std::vector<std::string> v_geom = split(parts[1],',');
979 std::string name = parts[2];
980 std::string label = parts[3];
982 MY_CHECKPOS("button",0);
983 MY_CHECKGEOM("button",1);
987 core::rect<s32> rect;
989 if (data->real_coordinates) {
990 pos = getRealCoordinateBasePos(v_pos);
991 geom = getRealCoordinateGeometry(v_geom);
992 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
995 pos = getElementBasePos(&v_pos);
996 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
997 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
999 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
1000 pos.X + geom.X, pos.Y + m_btn_height);
1003 if(!data->explicit_size)
1004 warningstream<<"invalid use of button without a size[] element"<<std::endl;
1006 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1012 258 + m_fields.size()
1014 spec.ftype = f_Button;
1015 if(type == "button_exit")
1016 spec.is_exit = true;
1018 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1019 data->current_parent, spec.fid, spec.flabel.c_str());
1021 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1022 e->setStyles(style);
1024 if (spec.fname == m_focused_element) {
1025 Environment->setFocus(e);
1028 m_fields.push_back(spec);
1031 errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl;
1034 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1036 std::vector<std::string> parts = split(element,';');
1038 if ((parts.size() >= 3 && parts.size() <= 5) ||
1039 (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
1040 std::vector<std::string> v_pos = split(parts[0],',');
1041 std::vector<std::string> v_geom = split(parts[1],',');
1042 std::string name = unescape_string(parts[2]);
1044 MY_CHECKPOS("background",0);
1045 MY_CHECKGEOM("background",1);
1050 if (data->real_coordinates) {
1051 pos = getRealCoordinateBasePos(v_pos);
1052 geom = getRealCoordinateGeometry(v_geom);
1054 pos = getElementBasePos(&v_pos);
1055 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1056 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1058 geom.X = stof(v_geom[0]) * spacing.X;
1059 geom.Y = stof(v_geom[1]) * spacing.Y;
1063 if (parts.size() >= 4 && is_yes(parts[3])) {
1064 if (data->real_coordinates) {
1065 pos = getRealCoordinateBasePos(v_pos) * -1;
1068 pos.X = stoi(v_pos[0]); //acts as offset
1069 pos.Y = stoi(v_pos[1]);
1074 core::rect<s32> middle;
1075 if (parts.size() >= 5) {
1076 std::vector<std::string> v_middle = split(parts[4], ',');
1077 if (v_middle.size() == 1) {
1078 s32 x = stoi(v_middle[0]);
1079 middle.UpperLeftCorner = core::vector2di(x, x);
1080 middle.LowerRightCorner = core::vector2di(-x, -x);
1081 } else if (v_middle.size() == 2) {
1082 s32 x = stoi(v_middle[0]);
1083 s32 y = stoi(v_middle[1]);
1084 middle.UpperLeftCorner = core::vector2di(x, y);
1085 middle.LowerRightCorner = core::vector2di(-x, -y);
1086 // `-x` is interpreted as `w - x`
1087 } else if (v_middle.size() == 4) {
1088 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1089 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1091 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1095 if (!data->explicit_size && !clip)
1096 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1102 258 + m_fields.size()
1105 core::rect<s32> rect;
1107 // no auto_clip => position like normal image
1108 rect = core::rect<s32>(pos, pos + geom);
1110 // it will be auto-clipped when drawing
1111 rect = core::rect<s32>(-pos, pos);
1114 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1115 rect, name, middle, m_tsrc, clip);
1117 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1119 e->setNotClipped(true);
1121 e->setVisible(false); // the element is drawn manually before all others
1123 m_backgrounds.push_back(e);
1124 m_fields.push_back(spec);
1127 errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl;
1130 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1132 std::vector<std::string> parts = split(element,';');
1134 data->table_options.clear();
1135 for (const std::string &part : parts) {
1136 // Parse table option
1137 std::string opt = unescape_string(part);
1138 data->table_options.push_back(GUITable::splitOption(opt));
1142 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1144 std::vector<std::string> parts = split(element,';');
1146 data->table_columns.clear();
1147 for (const std::string &part : parts) {
1148 std::vector<std::string> col_parts = split(part,',');
1149 GUITable::TableColumn column;
1150 // Parse column type
1151 if (!col_parts.empty())
1152 column.type = col_parts[0];
1153 // Parse column options
1154 for (size_t j = 1; j < col_parts.size(); ++j) {
1155 std::string opt = unescape_string(col_parts[j]);
1156 column.options.push_back(GUITable::splitOption(opt));
1158 data->table_columns.push_back(column);
1162 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1164 std::vector<std::string> parts = split(element,';');
1166 if (((parts.size() == 4) || (parts.size() == 5)) ||
1167 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1169 std::vector<std::string> v_pos = split(parts[0],',');
1170 std::vector<std::string> v_geom = split(parts[1],',');
1171 std::string name = parts[2];
1172 std::vector<std::string> items = split(parts[3],',');
1173 std::string str_initial_selection;
1174 std::string str_transparent = "false";
1176 if (parts.size() >= 5)
1177 str_initial_selection = parts[4];
1179 MY_CHECKPOS("table",0);
1180 MY_CHECKGEOM("table",1);
1185 if (data->real_coordinates) {
1186 pos = getRealCoordinateBasePos(v_pos);
1187 geom = getRealCoordinateGeometry(v_geom);
1189 pos = getElementBasePos(&v_pos);
1190 geom.X = stof(v_geom[0]) * spacing.X;
1191 geom.Y = stof(v_geom[1]) * spacing.Y;
1194 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1200 258 + m_fields.size()
1203 spec.ftype = f_Table;
1205 for (std::string &item : items) {
1206 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1209 //now really show table
1210 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1213 if (spec.fname == m_focused_element) {
1214 Environment->setFocus(e);
1217 e->setTable(data->table_options, data->table_columns, items);
1219 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1220 e->setDynamicData(data->table_dyndata[name]);
1223 if (!str_initial_selection.empty() && str_initial_selection != "0")
1224 e->setSelected(stoi(str_initial_selection));
1226 auto style = getDefaultStyleForElement("table", name);
1227 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1228 e->setOverrideFont(style.getFont());
1230 m_tables.emplace_back(spec, e);
1231 m_fields.push_back(spec);
1234 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1237 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1239 std::vector<std::string> parts = split(element,';');
1241 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1242 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1244 std::vector<std::string> v_pos = split(parts[0],',');
1245 std::vector<std::string> v_geom = split(parts[1],',');
1246 std::string name = parts[2];
1247 std::vector<std::string> items = split(parts[3],',');
1248 std::string str_initial_selection;
1249 std::string str_transparent = "false";
1251 if (parts.size() >= 5)
1252 str_initial_selection = parts[4];
1254 if (parts.size() >= 6)
1255 str_transparent = parts[5];
1257 MY_CHECKPOS("textlist",0);
1258 MY_CHECKGEOM("textlist",1);
1263 if (data->real_coordinates) {
1264 pos = getRealCoordinateBasePos(v_pos);
1265 geom = getRealCoordinateGeometry(v_geom);
1267 pos = getElementBasePos(&v_pos);
1268 geom.X = stof(v_geom[0]) * spacing.X;
1269 geom.Y = stof(v_geom[1]) * spacing.Y;
1272 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1278 258 + m_fields.size()
1281 spec.ftype = f_Table;
1283 for (std::string &item : items) {
1284 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1287 //now really show list
1288 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1291 if (spec.fname == m_focused_element) {
1292 Environment->setFocus(e);
1295 e->setTextList(items, is_yes(str_transparent));
1297 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1298 e->setDynamicData(data->table_dyndata[name]);
1301 if (!str_initial_selection.empty() && str_initial_selection != "0")
1302 e->setSelected(stoi(str_initial_selection));
1304 auto style = getDefaultStyleForElement("textlist", name);
1305 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1306 e->setOverrideFont(style.getFont());
1308 m_tables.emplace_back(spec, e);
1309 m_fields.push_back(spec);
1312 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1315 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1317 std::vector<std::string> parts = split(element, ';');
1319 if (parts.size() == 5 || parts.size() == 6 ||
1320 (parts.size() > 6 && m_formspec_version > FORMSPEC_API_VERSION))
1322 std::vector<std::string> v_pos = split(parts[0], ',');
1323 std::string name = parts[2];
1324 std::vector<std::string> items = split(parts[3], ',');
1325 std::string str_initial_selection = parts[4];
1327 if (parts.size() >= 6 && is_yes(parts[5]))
1328 m_dropdown_index_event[name] = true;
1330 MY_CHECKPOS("dropdown",0);
1334 core::rect<s32> rect;
1336 if (data->real_coordinates) {
1337 std::vector<std::string> v_geom = split(parts[1],',');
1339 if (v_geom.size() == 1)
1340 v_geom.emplace_back("1");
1342 MY_CHECKGEOM("dropdown",1);
1344 pos = getRealCoordinateBasePos(v_pos);
1345 geom = getRealCoordinateGeometry(v_geom);
1346 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1348 pos = getElementBasePos(&v_pos);
1350 s32 width = stof(parts[1]) * spacing.Y;
1352 rect = core::rect<s32>(pos.X, pos.Y,
1353 pos.X + width, pos.Y + (m_btn_height * 2));
1360 258 + m_fields.size()
1363 spec.ftype = f_DropDown;
1366 //now really show list
1367 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1370 if (spec.fname == m_focused_element) {
1371 Environment->setFocus(e);
1374 for (const std::string &item : items) {
1375 e->addItem(unescape_translate(unescape_string(
1376 utf8_to_wide(item))).c_str());
1379 if (!str_initial_selection.empty())
1380 e->setSelected(stoi(str_initial_selection)-1);
1382 auto style = getDefaultStyleForElement("dropdown", name);
1383 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1385 m_fields.push_back(spec);
1387 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1388 std::vector<std::string> &values = m_dropdowns.back().second;
1389 for (const std::string &item : items) {
1390 values.push_back(unescape_string(item));
1395 errorstream << "Invalid dropdown element(" << parts.size() << "): '" << element
1396 << "'" << std::endl;
1399 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1401 std::vector<std::string> parts = split(element,';');
1402 if (parts.size() == 2 ||
1403 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1404 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1408 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1410 std::vector<std::string> parts = split(element,';');
1412 if (parts.size() == 4 ||
1413 (parts.size() > 4 && m_formspec_version > FORMSPEC_API_VERSION))
1415 std::vector<std::string> v_pos = split(parts[0],',');
1416 std::vector<std::string> v_geom = split(parts[1],',');
1417 std::string name = parts[2];
1418 std::string label = parts[3];
1420 MY_CHECKPOS("pwdfield",0);
1421 MY_CHECKGEOM("pwdfield",1);
1426 if (data->real_coordinates) {
1427 pos = getRealCoordinateBasePos(v_pos);
1428 geom = getRealCoordinateGeometry(v_geom);
1430 pos = getElementBasePos(&v_pos);
1433 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1435 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1436 pos.Y -= m_btn_height;
1437 geom.Y = m_btn_height*2;
1440 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1442 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1448 258 + m_fields.size(),
1454 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1455 data->current_parent, spec.fid);
1457 if (spec.fname == m_focused_element) {
1458 Environment->setFocus(e);
1461 if (label.length() >= 1) {
1462 int font_height = g_fontengine->getTextHeight();
1463 rect.UpperLeftCorner.Y -= font_height;
1464 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1465 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1466 data->current_parent, 0);
1469 e->setPasswordBox(true,L'*');
1471 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1472 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1473 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1474 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1475 e->setOverrideFont(style.getFont());
1478 evt.EventType = EET_KEY_INPUT_EVENT;
1479 evt.KeyInput.Key = KEY_END;
1480 evt.KeyInput.Char = 0;
1481 evt.KeyInput.Control = false;
1482 evt.KeyInput.Shift = false;
1483 evt.KeyInput.PressedDown = true;
1486 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1487 // warning referring to field_close_on_enter[]!
1489 m_fields.push_back(spec);
1492 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1495 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1496 core::rect<s32> &rect, bool is_multiline)
1498 bool is_editable = !spec.fname.empty();
1499 if (!is_editable && !is_multiline) {
1500 // spec field id to 0, this stops submit searching for a value that isn't there
1501 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1502 data->current_parent, 0);
1508 } else if (is_multiline &&
1509 spec.fdefault.empty() && !spec.flabel.empty()) {
1510 // Multiline textareas: swap default and label for backwards compat
1511 spec.flabel.swap(spec.fdefault);
1514 gui::IGUIEditBox *e = nullptr;
1515 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1516 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1518 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1519 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1520 data->current_parent, spec.fid, rect, is_editable, is_multiline);
1523 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1524 data->current_parent, spec.fid, rect, is_editable, true);
1525 } else if (is_editable) {
1526 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1527 data->current_parent, spec.fid);
1532 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1535 if (is_editable && spec.fname == m_focused_element)
1536 Environment->setFocus(e);
1539 e->setMultiLine(true);
1540 e->setWordWrap(true);
1541 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1544 evt.EventType = EET_KEY_INPUT_EVENT;
1545 evt.KeyInput.Key = KEY_END;
1546 evt.KeyInput.Char = 0;
1547 evt.KeyInput.Control = 0;
1548 evt.KeyInput.Shift = 0;
1549 evt.KeyInput.PressedDown = true;
1553 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1554 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1555 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1556 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1557 e->setDrawBackground(false);
1559 e->setOverrideFont(style.getFont());
1564 if (!spec.flabel.empty()) {
1565 int font_height = g_fontengine->getTextHeight();
1566 rect.UpperLeftCorner.Y -= font_height;
1567 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1568 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1569 rect, false, true, data->current_parent, 0);
1572 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1576 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1577 std::vector<std::string> &parts)
1579 std::string name = parts[0];
1580 std::string label = parts[1];
1581 std::string default_val = parts[2];
1583 core::rect<s32> rect;
1585 if (data->explicit_size)
1586 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1588 v2s32 pos = getElementBasePos(nullptr);
1589 pos.Y = (data->simple_field_count + 2) * 60;
1590 v2s32 size = DesiredRect.getSize();
1592 rect = core::rect<s32>(
1593 size.X / 2 - 150, pos.Y,
1594 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1599 default_val = m_form_src->resolveText(default_val);
1602 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1607 utf8_to_wide(unescape_string(default_val)),
1608 258 + m_fields.size(),
1613 createTextField(data, spec, rect, false);
1615 m_fields.push_back(spec);
1617 data->simple_field_count++;
1620 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1621 const std::string &type)
1623 std::vector<std::string> v_pos = split(parts[0],',');
1624 std::vector<std::string> v_geom = split(parts[1],',');
1625 std::string name = parts[2];
1626 std::string label = parts[3];
1627 std::string default_val = parts[4];
1629 MY_CHECKPOS(type,0);
1630 MY_CHECKGEOM(type,1);
1635 if (data->real_coordinates) {
1636 pos = getRealCoordinateBasePos(v_pos);
1637 geom = getRealCoordinateGeometry(v_geom);
1639 pos = getElementBasePos(&v_pos);
1642 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1644 if (type == "textarea")
1646 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1647 pos.Y += m_btn_height;
1651 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1652 pos.Y -= m_btn_height;
1653 geom.Y = m_btn_height*2;
1657 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1659 if(!data->explicit_size)
1660 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1663 default_val = m_form_src->resolveText(default_val);
1666 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1671 utf8_to_wide(unescape_string(default_val)),
1672 258 + m_fields.size(),
1677 createTextField(data, spec, rect, type == "textarea");
1679 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1680 // warning referring to field_close_on_enter[]!
1682 m_fields.push_back(spec);
1685 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1686 const std::string &type)
1688 std::vector<std::string> parts = split(element,';');
1690 if (parts.size() == 3 || parts.size() == 4) {
1691 parseSimpleField(data,parts);
1695 if ((parts.size() == 5) ||
1696 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1698 parseTextArea(data,parts,type);
1701 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1704 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1706 std::vector<std::string> parts = split(element, ';');
1708 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1709 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1713 std::vector<std::string> v_pos = split(parts[0], ',');
1714 std::vector<std::string> v_geom = split(parts[1], ',');
1715 std::string name = parts[2];
1716 std::string text = parts[3];
1718 MY_CHECKPOS("hypertext", 0);
1719 MY_CHECKGEOM("hypertext", 1);
1724 if (data->real_coordinates) {
1725 pos = getRealCoordinateBasePos(v_pos);
1726 geom = getRealCoordinateGeometry(v_geom);
1728 pos = getElementBasePos(&v_pos);
1731 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1732 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1733 pos.Y += m_btn_height;
1736 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1739 text = m_form_src->resolveText(text);
1743 utf8_to_wide(unescape_string(text)),
1745 258 + m_fields.size()
1748 spec.ftype = f_HyperText;
1749 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1750 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1753 m_fields.push_back(spec);
1756 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1758 std::vector<std::string> parts = split(element,';');
1760 if ((parts.size() == 2) ||
1761 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1763 std::vector<std::string> v_pos = split(parts[0],',');
1764 std::string text = parts[1];
1766 MY_CHECKPOS("label",0);
1768 if(!data->explicit_size)
1769 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1771 std::vector<std::string> lines = split(text, '\n');
1773 auto style = getDefaultStyleForElement("label", "");
1774 gui::IGUIFont *font = style.getFont();
1778 for (unsigned int i = 0; i != lines.size(); i++) {
1779 std::wstring wlabel_colors = translate_string(
1780 utf8_to_wide(unescape_string(lines[i])));
1781 // Without color escapes to get the font dimensions
1782 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1784 core::rect<s32> rect;
1786 if (data->real_coordinates) {
1787 // Lines are spaced at the distance of 1/2 imgsize.
1788 // This alows lines that line up with the new elements
1789 // easily without sacrificing good line distance. If
1790 // it was one whole imgsize, it would have too much
1792 v2s32 pos = getRealCoordinateBasePos(v_pos);
1794 // Labels are positioned by their center, not their top.
1795 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1797 rect = core::rect<s32>(
1799 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1803 // Lines are spaced at the nominal distance of
1804 // 2/5 inventory slot, even if the font doesn't
1805 // quite match that. This provides consistent
1806 // form layout, at the expense of sometimes
1807 // having sub-optimal spacing for the font.
1808 // We multiply by 2 and then divide by 5, rather
1809 // than multiply by 0.4, to get exact results
1810 // in the integer cases: 0.4 is not exactly
1811 // representable in binary floating point.
1813 v2s32 pos = getElementBasePos(nullptr);
1814 pos.X += stof(v_pos[0]) * spacing.X;
1815 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1817 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1819 rect = core::rect<s32>(
1820 pos.X, pos.Y - m_btn_height,
1821 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1822 pos.Y + m_btn_height);
1829 258 + m_fields.size(),
1832 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1833 spec.flabel.c_str(), rect, false, false, data->current_parent,
1835 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1837 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1838 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1839 e->setOverrideFont(font);
1841 m_fields.push_back(spec);
1843 // labels should let events through
1845 m_clickthrough_elements.push_back(e);
1850 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1851 << "'" << std::endl;
1854 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1856 std::vector<std::string> parts = split(element,';');
1858 if ((parts.size() == 2) ||
1859 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1861 std::vector<std::string> v_pos = split(parts[0],',');
1862 std::wstring text = unescape_translate(
1863 unescape_string(utf8_to_wide(parts[1])));
1865 MY_CHECKPOS("vertlabel",1);
1867 auto style = getDefaultStyleForElement("vertlabel", "", "label");
1868 gui::IGUIFont *font = style.getFont();
1873 core::rect<s32> rect;
1875 if (data->real_coordinates) {
1876 pos = getRealCoordinateBasePos(v_pos);
1878 // Vertlabels are positioned by center, not left.
1879 pos.X -= imgsize.X / 2;
1881 // We use text.length + 1 because without it, the rect
1882 // isn't quite tall enough and cuts off the text.
1883 rect = core::rect<s32>(pos.X, pos.Y,
1885 pos.Y + font_line_height(font) *
1886 (text.length() + 1));
1889 pos = getElementBasePos(&v_pos);
1891 // As above, the length must be one longer. The width of
1892 // the rect (15 pixels) seems rather arbitrary, but
1893 // changing it might break something.
1894 rect = core::rect<s32>(
1895 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1897 font_line_height(font) *
1898 (text.length() + 1) +
1899 ((imgsize.Y/2) - m_btn_height));
1902 if(!data->explicit_size)
1903 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1907 for (wchar_t i : text) {
1916 258 + m_fields.size()
1918 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1919 rect, false, false, data->current_parent, spec.fid);
1920 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1922 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1923 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1924 e->setOverrideFont(font);
1926 m_fields.push_back(spec);
1928 // vertlabels should let events through
1930 m_clickthrough_elements.push_back(e);
1933 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1936 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1937 const std::string &type)
1939 std::vector<std::string> parts = split(element,';');
1941 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1942 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1944 std::vector<std::string> v_pos = split(parts[0],',');
1945 std::vector<std::string> v_geom = split(parts[1],',');
1946 std::string image_name = parts[2];
1947 std::string name = parts[3];
1948 std::string label = parts[4];
1950 MY_CHECKPOS("imagebutton",0);
1951 MY_CHECKGEOM("imagebutton",1);
1953 std::string pressed_image_name;
1955 if (parts.size() >= 8) {
1956 pressed_image_name = parts[7];
1962 if (data->real_coordinates) {
1963 pos = getRealCoordinateBasePos(v_pos);
1964 geom = getRealCoordinateGeometry(v_geom);
1966 pos = getElementBasePos(&v_pos);
1967 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1968 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1971 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1974 if (!data->explicit_size)
1975 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1977 image_name = unescape_string(image_name);
1978 pressed_image_name = unescape_string(pressed_image_name);
1980 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1985 utf8_to_wide(image_name),
1986 258 + m_fields.size()
1988 spec.ftype = f_Button;
1989 if (type == "image_button_exit")
1990 spec.is_exit = true;
1992 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1993 data->current_parent, spec.fid, spec.flabel.c_str());
1995 if (spec.fname == m_focused_element) {
1996 Environment->setFocus(e);
1999 auto style = getStyleForElement("image_button", spec.fname);
2001 // Override style properties with values specified directly in the element
2002 if (!image_name.empty())
2003 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
2005 if (!pressed_image_name.empty())
2006 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
2008 if (parts.size() >= 7) {
2009 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
2010 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
2013 e->setStyles(style);
2014 e->setScaleImage(true);
2016 m_fields.push_back(spec);
2020 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2023 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2025 std::vector<std::string> parts = split(element, ';');
2027 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
2028 data->real_coordinates) || ((parts.size() > 6) &&
2029 (m_formspec_version > FORMSPEC_API_VERSION)))
2031 std::vector<std::string> v_pos = split(parts[0],',');
2033 // If we're using real coordinates, add an extra field for height.
2034 // Width is not here because tabs are the width of the text, and
2035 // there's no reason to change that.
2037 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2038 bool auto_width = true;
2039 if (parts.size() == 7) {
2042 v_geom = split(parts[1], ',');
2043 if (v_geom.size() == 1)
2044 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2049 std::string name = parts[i+1];
2050 std::vector<std::string> buttons = split(parts[i+2], ',');
2051 std::string str_index = parts[i+3];
2052 bool show_background = true;
2053 bool show_border = true;
2054 int tab_index = stoi(str_index) - 1;
2056 MY_CHECKPOS("tabheader", 0);
2058 if (parts.size() == 6 + i) {
2059 if (parts[4+i] == "true")
2060 show_background = false;
2061 if (parts[5+i] == "false")
2062 show_border = false;
2069 258 + m_fields.size()
2072 spec.ftype = f_TabHeader;
2077 if (data->real_coordinates) {
2078 pos = getRealCoordinateBasePos(v_pos);
2080 geom = getRealCoordinateGeometry(v_geom);
2081 // Set default height
2082 if (parts.size() <= 6)
2083 geom.Y = m_btn_height * 2;
2084 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2086 geom.X = DesiredRect.getWidth(); // Set automatic width
2088 MY_CHECKGEOM("tabheader", 1);
2090 v2f32 pos_f = pos_offset * spacing;
2091 pos_f.X += stof(v_pos[0]) * spacing.X;
2092 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2093 pos = v2s32(pos_f.X, pos_f.Y);
2095 geom.Y = m_btn_height * 2;
2096 geom.X = DesiredRect.getWidth();
2099 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2102 gui::IGUITabControl *e = Environment->addTabControl(rect,
2103 data->current_parent, show_background, show_border, spec.fid);
2104 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2105 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2106 e->setTabHeight(geom.Y);
2108 auto style = getDefaultStyleForElement("tabheader", name);
2109 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2111 for (const std::string &button : buttons) {
2112 auto tab = e->addTab(unescape_translate(unescape_string(
2113 utf8_to_wide(button))).c_str(), -1);
2114 if (style.isNotDefault(StyleSpec::BGCOLOR))
2115 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2117 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2120 if ((tab_index >= 0) &&
2121 (buttons.size() < INT_MAX) &&
2122 (tab_index < (int) buttons.size()))
2123 e->setActiveTab(tab_index);
2125 m_fields.push_back(spec);
2128 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2129 << element << "'" << std::endl;
2132 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2134 if (m_client == 0) {
2135 warningstream << "invalid use of item_image_button with m_client==0"
2140 std::vector<std::string> parts = split(element,';');
2142 if ((parts.size() == 5) ||
2143 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2145 std::vector<std::string> v_pos = split(parts[0],',');
2146 std::vector<std::string> v_geom = split(parts[1],',');
2147 std::string item_name = parts[2];
2148 std::string name = parts[3];
2149 std::string label = parts[4];
2151 label = unescape_string(label);
2152 item_name = unescape_string(item_name);
2154 MY_CHECKPOS("itemimagebutton",0);
2155 MY_CHECKGEOM("itemimagebutton",1);
2160 if (data->real_coordinates) {
2161 pos = getRealCoordinateBasePos(v_pos);
2162 geom = getRealCoordinateGeometry(v_geom);
2164 pos = getElementBasePos(&v_pos);
2165 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2166 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2169 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2171 if(!data->explicit_size)
2172 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2174 IItemDefManager *idef = m_client->idef();
2176 item.deSerialize(item_name, idef);
2179 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2180 m_default_tooltip_bgcolor,
2181 m_default_tooltip_color);
2183 // the spec for the button
2186 utf8_to_wide(label),
2187 utf8_to_wide(item_name),
2188 258 + m_fields.size(),
2192 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2193 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2194 item_name, m_client);
2196 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2197 e_btn->setStyles(style);
2199 if (spec_btn.fname == m_focused_element) {
2200 Environment->setFocus(e_btn);
2203 spec_btn.ftype = f_Button;
2204 rect += data->basepos-padding;
2205 spec_btn.rect = rect;
2206 m_fields.push_back(spec_btn);
2209 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2212 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2214 std::vector<std::string> parts = split(element,';');
2216 if ((parts.size() == 3) ||
2217 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2219 std::vector<std::string> v_pos = split(parts[0],',');
2220 std::vector<std::string> v_geom = split(parts[1],',');
2222 MY_CHECKPOS("box",0);
2223 MY_CHECKGEOM("box",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 video::SColor tmp_color;
2239 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2244 258 + m_fields.size(),
2249 core::rect<s32> rect(pos, pos + geom);
2251 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid,
2254 auto style = getDefaultStyleForElement("box", spec.fname);
2255 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2259 m_fields.push_back(spec);
2262 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2266 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2269 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2271 std::vector<std::string> parts = split(element,';');
2272 const u32 parameter_count = parts.size();
2274 if ((parameter_count > 2 && m_formspec_version < 3) ||
2275 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2276 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2277 << element << "'" << std::endl;
2282 if (parameter_count >= 1 && parts[0] != "")
2283 parseColorString(parts[0], m_bgcolor, false);
2286 if (parameter_count >= 2) {
2287 if (parts[1] == "both") {
2288 m_bgnonfullscreen = true;
2289 m_bgfullscreen = true;
2290 } else if (parts[1] == "neither") {
2291 m_bgnonfullscreen = false;
2292 m_bgfullscreen = false;
2293 } else if (parts[1] != "" || m_formspec_version < 3) {
2294 m_bgfullscreen = is_yes(parts[1]);
2295 m_bgnonfullscreen = !m_bgfullscreen;
2300 if (parameter_count >= 3 && parts[2] != "")
2301 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2304 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2306 std::vector<std::string> parts = split(element,';');
2308 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2309 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2311 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2312 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2314 if (parts.size() >= 3) {
2315 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2317 data->inventorylist_options.slotborder = true;
2320 if (parts.size() == 5) {
2321 video::SColor tmp_color;
2323 if (parseColorString(parts[3], tmp_color, false))
2324 m_default_tooltip_bgcolor = tmp_color;
2325 if (parseColorString(parts[4], tmp_color, false))
2326 m_default_tooltip_color = tmp_color;
2329 // update all already parsed inventorylists
2330 for (GUIInventoryList *e : m_inventorylists) {
2331 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2332 data->inventorylist_options.slotbg_h);
2333 e->setSlotBorders(data->inventorylist_options.slotborder,
2334 data->inventorylist_options.slotbordercolor);
2338 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2341 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2343 std::vector<std::string> parts = split(element,';');
2344 if (parts.size() < 2) {
2345 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2346 << element << "'" << std::endl;
2350 // Get mode and check size
2351 bool rect_mode = parts[0].find(',') != std::string::npos;
2352 size_t base_size = rect_mode ? 3 : 2;
2353 if (parts.size() != base_size && parts.size() != base_size + 2) {
2354 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2355 << element << "'" << std::endl;
2360 video::SColor bgcolor = m_default_tooltip_bgcolor;
2361 video::SColor color = m_default_tooltip_color;
2362 if (parts.size() == base_size + 2 &&
2363 (!parseColorString(parts[base_size], bgcolor, false) ||
2364 !parseColorString(parts[base_size + 1], color, false))) {
2365 errorstream << "Invalid color in tooltip element(" << parts.size()
2366 << "): '" << element << "'" << std::endl;
2370 // Make tooltip spec
2371 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2372 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2376 std::vector<std::string> v_pos = split(parts[0], ',');
2377 std::vector<std::string> v_geom = split(parts[1], ',');
2379 MY_CHECKPOS("tooltip", 0);
2380 MY_CHECKGEOM("tooltip", 1);
2385 if (data->real_coordinates) {
2386 pos = getRealCoordinateBasePos(v_pos);
2387 geom = getRealCoordinateGeometry(v_geom);
2389 pos = getElementBasePos(&v_pos);
2390 geom.X = stof(v_geom[0]) * spacing.X;
2391 geom.Y = stof(v_geom[1]) * spacing.Y;
2394 FieldSpec fieldspec(
2398 258 + m_fields.size()
2401 core::rect<s32> rect(pos, pos + geom);
2403 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2404 data->current_parent, fieldspec.fid, rect);
2406 // the element the rect tooltip is bound to should not block mouse-clicks
2407 e->setVisible(false);
2409 m_fields.push_back(fieldspec);
2410 m_tooltip_rects.emplace_back(e, spec);
2413 m_tooltips[parts[0]] = spec;
2417 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2423 std::vector<std::string> parts = split(data,'[');
2425 if (parts.size() < 2) {
2429 if (trim(parts[0]) != "formspec_version") {
2433 if (is_number(parts[1])) {
2434 m_formspec_version = mystoi(parts[1]);
2441 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2443 if (element.empty())
2446 std::vector<std::string> parts = split(element,'[');
2448 if (parts.size() < 2)
2451 std::string type = trim(parts[0]);
2452 std::string description = trim(parts[1]);
2454 if (type != "size" && type != "invsize")
2457 if (type == "invsize")
2458 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2460 parseSize(data, description);
2465 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2467 if (element.empty())
2470 std::vector<std::string> parts = split(element, '[');
2472 if (parts.size() != 2)
2475 std::string type = trim(parts[0]);
2476 std::string description = trim(parts[1]);
2478 if (type != "position")
2481 parsePosition(data, description);
2486 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2488 std::vector<std::string> parts = split(element, ',');
2490 if (parts.size() == 2) {
2491 data->offset.X = stof(parts[0]);
2492 data->offset.Y = stof(parts[1]);
2496 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2499 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2501 if (element.empty())
2504 std::vector<std::string> parts = split(element, '[');
2506 if (parts.size() != 2)
2509 std::string type = trim(parts[0]);
2510 std::string description = trim(parts[1]);
2512 if (type != "anchor")
2515 parseAnchor(data, description);
2520 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2522 std::vector<std::string> parts = split(element, ',');
2524 if (parts.size() == 2) {
2525 data->anchor.X = stof(parts[0]);
2526 data->anchor.Y = stof(parts[1]);
2530 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2531 << "'" << std::endl;
2534 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2536 std::vector<std::string> parts = split(element, ';');
2538 if (parts.size() < 2) {
2539 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2540 << "'" << std::endl;
2547 for (size_t i = 1; i < parts.size(); i++) {
2548 size_t equal_pos = parts[i].find('=');
2549 if (equal_pos == std::string::npos) {
2550 errorstream << "Invalid style element (Property missing value): '" << element
2551 << "'" << std::endl;
2555 std::string propname = trim(parts[i].substr(0, equal_pos));
2556 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2558 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2560 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2561 if (prop == StyleSpec::NONE) {
2562 if (property_warned.find(propname) != property_warned.end()) {
2563 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2565 << "'" << std::endl;
2566 property_warned.insert(propname);
2571 spec.set(prop, value);
2574 std::vector<std::string> selectors = split(parts[0], ',');
2575 for (size_t sel = 0; sel < selectors.size(); sel++) {
2576 std::string selector = trim(selectors[sel]);
2578 // Copy the style properties to a new StyleSpec
2579 // This allows a separate state mask per-selector
2580 StyleSpec selector_spec = spec;
2582 // Parse state information, if it exists
2583 bool state_valid = true;
2584 size_t state_pos = selector.find(':');
2585 if (state_pos != std::string::npos) {
2586 std::string state_str = selector.substr(state_pos + 1);
2587 selector = selector.substr(0, state_pos);
2589 if (state_str.empty()) {
2590 errorstream << "Invalid style element (Invalid state): '" << element
2591 << "'" << std::endl;
2592 state_valid = false;
2594 std::vector<std::string> states = split(state_str, '+');
2595 for (std::string &state : states) {
2596 StyleSpec::State converted = StyleSpec::getStateByName(state);
2597 if (converted == StyleSpec::STATE_INVALID) {
2598 infostream << "Unknown style state " << state <<
2599 " in element '" << element << "'" << std::endl;
2600 state_valid = false;
2604 selector_spec.addState(converted);
2610 // Skip this selector
2615 theme_by_type[selector].push_back(selector_spec);
2617 theme_by_name[selector].push_back(selector_spec);
2620 // Backwards-compatibility for existing _hovered/_pressed properties
2621 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2622 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2623 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2624 StyleSpec hover_spec;
2625 hover_spec.addState(StyleSpec::STATE_HOVERED);
2627 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2628 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2630 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2631 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2633 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2634 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2638 theme_by_type[selector].push_back(hover_spec);
2640 theme_by_name[selector].push_back(hover_spec);
2643 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2644 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2645 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2646 StyleSpec press_spec;
2647 press_spec.addState(StyleSpec::STATE_PRESSED);
2649 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2650 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2652 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2653 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2655 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2656 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2660 theme_by_type[selector].push_back(press_spec);
2662 theme_by_name[selector].push_back(press_spec);
2670 void GUIFormSpecMenu::parseSetFocus(const std::string &element)
2672 std::vector<std::string> parts = split(element, ';');
2674 if (parts.size() <= 2 ||
2675 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION))
2677 if (m_is_form_regenerated)
2678 return; // Never focus on resizing
2680 bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
2681 if (force_focus || m_text_dst->m_formname != m_last_formname)
2687 errorstream << "Invalid set_focus element (" << parts.size() << "): '" << element
2688 << "'" << std::endl;
2691 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2694 if (element.empty())
2697 if (parseVersionDirect(element))
2700 size_t pos = element.find('[');
2701 if (pos == std::string::npos)
2704 std::string type = trim(element.substr(0, pos));
2705 std::string description = element.substr(pos+1);
2707 if (type == "container") {
2708 parseContainer(data, description);
2712 if (type == "container_end") {
2713 parseContainerEnd(data);
2717 if (type == "list") {
2718 parseList(data, description);
2722 if (type == "listring") {
2723 parseListRing(data, description);
2727 if (type == "checkbox") {
2728 parseCheckbox(data, description);
2732 if (type == "image") {
2733 parseImage(data, description);
2737 if (type == "animated_image") {
2738 parseAnimatedImage(data, description);
2742 if (type == "item_image") {
2743 parseItemImage(data, description);
2747 if (type == "button" || type == "button_exit") {
2748 parseButton(data, description, type);
2752 if (type == "background" || type == "background9") {
2753 parseBackground(data, description);
2757 if (type == "tableoptions"){
2758 parseTableOptions(data,description);
2762 if (type == "tablecolumns"){
2763 parseTableColumns(data,description);
2767 if (type == "table"){
2768 parseTable(data,description);
2772 if (type == "textlist"){
2773 parseTextList(data,description);
2777 if (type == "dropdown"){
2778 parseDropDown(data,description);
2782 if (type == "field_close_on_enter") {
2783 parseFieldCloseOnEnter(data, description);
2787 if (type == "pwdfield") {
2788 parsePwdField(data,description);
2792 if ((type == "field") || (type == "textarea")){
2793 parseField(data,description,type);
2797 if (type == "hypertext") {
2798 parseHyperText(data,description);
2802 if (type == "label") {
2803 parseLabel(data,description);
2807 if (type == "vertlabel") {
2808 parseVertLabel(data,description);
2812 if (type == "item_image_button") {
2813 parseItemImageButton(data,description);
2817 if ((type == "image_button") || (type == "image_button_exit")) {
2818 parseImageButton(data,description,type);
2822 if (type == "tabheader") {
2823 parseTabHeader(data,description);
2827 if (type == "box") {
2828 parseBox(data,description);
2832 if (type == "bgcolor") {
2833 parseBackgroundColor(data,description);
2837 if (type == "listcolors") {
2838 parseListColors(data,description);
2842 if (type == "tooltip") {
2843 parseTooltip(data,description);
2847 if (type == "scrollbar") {
2848 parseScrollBar(data, description);
2852 if (type == "real_coordinates") {
2853 data->real_coordinates = is_yes(description);
2857 if (type == "style") {
2858 parseStyle(data, description, false);
2862 if (type == "style_type") {
2863 parseStyle(data, description, true);
2867 if (type == "scrollbaroptions") {
2868 parseScrollBarOptions(data, description);
2872 if (type == "scroll_container") {
2873 parseScrollContainer(data, description);
2877 if (type == "scroll_container_end") {
2878 parseScrollContainerEnd(data);
2882 if (type == "set_focus") {
2883 parseSetFocus(description);
2888 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2892 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2894 // Useless to regenerate without a screensize
2895 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2901 // Preserve stuff only on same form, not on a new form.
2902 if (m_text_dst->m_formname == m_last_formname) {
2903 // Preserve tables/textlists
2904 for (auto &m_table : m_tables) {
2905 std::string tablename = m_table.first.fname;
2906 GUITable *table = m_table.second;
2907 mydata.table_dyndata[tablename] = table->getDynamicData();
2911 gui::IGUIElement *focused_element = Environment->getFocus();
2912 if (focused_element && focused_element->getParent() == this) {
2913 s32 focused_id = focused_element->getID();
2914 if (focused_id > 257) {
2915 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2916 if (field.fid == focused_id) {
2917 m_focused_element = field.fname;
2924 // Don't keep old focus value
2925 m_focused_element = "";
2931 for (auto &table_it : m_tables)
2932 table_it.second->drop();
2933 for (auto &inventorylist_it : m_inventorylists)
2934 inventorylist_it->drop();
2935 for (auto &checkbox_it : m_checkboxes)
2936 checkbox_it.second->drop();
2937 for (auto &scrollbar_it : m_scrollbars)
2938 scrollbar_it.second->drop();
2939 for (auto &background_it : m_backgrounds)
2940 background_it->drop();
2941 for (auto &tooltip_rect_it : m_tooltip_rects)
2942 tooltip_rect_it.first->drop();
2943 for (auto &clickthrough_it : m_clickthrough_elements)
2944 clickthrough_it->drop();
2945 for (auto &scroll_container_it : m_scroll_containers)
2946 scroll_container_it.second->drop();
2948 mydata.size = v2s32(100, 100);
2949 mydata.screensize = screensize;
2950 mydata.offset = v2f32(0.5f, 0.5f);
2951 mydata.anchor = v2f32(0.5f, 0.5f);
2952 mydata.simple_field_count = 0;
2954 // Base position of contents of form
2955 mydata.basepos = getBasePos();
2957 // the parent for the parsed elements
2958 mydata.current_parent = this;
2960 m_inventorylists.clear();
2961 m_backgrounds.clear();
2963 m_checkboxes.clear();
2964 m_scrollbars.clear();
2967 m_tooltip_rects.clear();
2968 m_inventory_rings.clear();
2969 m_dropdowns.clear();
2970 m_scroll_containers.clear();
2971 theme_by_name.clear();
2972 theme_by_type.clear();
2973 m_clickthrough_elements.clear();
2974 field_close_on_enter.clear();
2975 m_dropdown_index_event.clear();
2977 m_bgnonfullscreen = true;
2978 m_bgfullscreen = false;
2980 m_formspec_version = 1;
2983 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2984 m_bgcolor = video::SColor(
2985 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2986 clamp_u8(myround(formspec_bgcolor.X)),
2987 clamp_u8(myround(formspec_bgcolor.Y)),
2988 clamp_u8(myround(formspec_bgcolor.Z))
2993 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2994 m_fullscreen_bgcolor = video::SColor(
2995 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2996 clamp_u8(myround(formspec_bgcolor.X)),
2997 clamp_u8(myround(formspec_bgcolor.Y)),
2998 clamp_u8(myround(formspec_bgcolor.Z))
3002 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3003 m_default_tooltip_color = video::SColor(255,255,255,255);
3007 assert(!m_tooltip_element);
3008 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3009 m_tooltip_element = gui::StaticText::add(Environment, L"",
3010 core::rect<s32>(0, 0, 110, 18));
3011 m_tooltip_element->enableOverrideColor(true);
3012 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3013 m_tooltip_element->setDrawBackground(true);
3014 m_tooltip_element->setDrawBorder(true);
3015 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3016 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3017 m_tooltip_element->setWordWrap(false);
3018 //we're not parent so no autograb for this one!
3019 m_tooltip_element->grab();
3022 std::vector<std::string> elements = split(m_formspec_string,']');
3025 /* try to read version from first element only */
3026 if (!elements.empty()) {
3027 if (parseVersionDirect(elements[0])) {
3032 /* we need size first in order to calculate image scale */
3033 mydata.explicit_size = false;
3034 for (; i< elements.size(); i++) {
3035 if (!parseSizeDirect(&mydata, elements[i])) {
3040 /* "position" element is always after "size" element if it used */
3041 for (; i< elements.size(); i++) {
3042 if (!parsePositionDirect(&mydata, elements[i])) {
3047 /* "anchor" element is always after "position" (or "size" element) if it used */
3048 for (; i< elements.size(); i++) {
3049 if (!parseAnchorDirect(&mydata, elements[i])) {
3054 /* "no_prepend" element is always after "position" (or "size" element) if it used */
3055 bool enable_prepends = true;
3056 for (; i < elements.size(); i++) {
3057 if (elements[i].empty())
3060 std::vector<std::string> parts = split(elements[i], '[');
3061 if (trim(parts[0]) == "no_prepend")
3062 enable_prepends = false;
3067 /* Copy of the "real_coordinates" element for after the form size. */
3068 mydata.real_coordinates = m_formspec_version >= 2;
3069 for (; i < elements.size(); i++) {
3070 std::vector<std::string> parts = split(elements[i], '[');
3071 std::string name = trim(parts[0]);
3072 if (name != "real_coordinates" || parts.size() != 2)
3073 break; // Invalid format
3075 mydata.real_coordinates = is_yes(trim(parts[1]));
3078 if (mydata.explicit_size) {
3079 // compute scaling for specified form size
3081 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3082 v2u32 delta = current_screensize - m_lockscreensize;
3084 if (current_screensize.Y > m_lockscreensize.Y)
3089 if (current_screensize.X > m_lockscreensize.X)
3094 offset = v2s32(delta.X,delta.Y);
3096 mydata.screensize = m_lockscreensize;
3098 offset = v2s32(0,0);
3101 double gui_scaling = g_settings->getFloat("gui_scaling");
3102 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3106 // In fixed-size mode, inventory image size
3107 // is 0.53 inch multiplied by the gui_scaling
3108 // config parameter. This magic size is chosen
3109 // to make the main menu (15.5 inventory images
3110 // wide, including border) just fit into the
3111 // default window (800 pixels wide) at 96 DPI
3112 // and default scaling (1.00).
3113 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3115 // Variables for the maximum imgsize that can fit in the screen.
3116 double fitx_imgsize;
3117 double fity_imgsize;
3119 // Pad the screensize with 5% of the screensize on all sides to ensure
3120 // that even the largest formspecs don't touch the screen borders.
3121 v2f padded_screensize(
3122 mydata.screensize.X * 0.9f,
3123 mydata.screensize.Y * 0.9f
3126 if (mydata.real_coordinates) {
3127 fitx_imgsize = padded_screensize.X / mydata.invsize.X;
3128 fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
3130 // The maximum imgsize in the old coordinate system also needs to
3131 // factor in padding and spacing along with 0.1 inventory slot spare
3132 // and help text space, hence the magic numbers.
3133 fitx_imgsize = padded_screensize.X /
3134 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3135 fity_imgsize = padded_screensize.Y /
3136 ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
3140 // In Android, the preferred imgsize should be larger to accommodate the
3141 // smaller screensize.
3142 double prefer_imgsize = padded_screensize.Y / 10 * gui_scaling;
3144 // Desktop computers have more space, so try to fit 15 coordinates.
3145 double prefer_imgsize = padded_screensize.Y / 15 * gui_scaling;
3147 // Try to use the preferred imgsize, but if that's bigger than the maximum
3148 // size, use the maximum size.
3149 use_imgsize = std::min(prefer_imgsize,
3150 std::min(fitx_imgsize, fity_imgsize));
3153 // Everything else is scaled in proportion to the
3154 // inventory image size. The inventory slot spacing
3155 // is 5/4 image size horizontally and 15/13 image size
3156 // vertically. The padding around the form (incorporating
3157 // the border of the outer inventory slots) is 3/8
3158 // image size. Font height (baseline to baseline)
3159 // is 2/5 vertical inventory slot spacing, and button
3160 // half-height is 7/8 of font height.
3161 imgsize = v2s32(use_imgsize, use_imgsize);
3162 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3163 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3164 m_btn_height = use_imgsize*15.0/13 * 0.35;
3166 m_font = g_fontengine->getFont();
3168 if (mydata.real_coordinates) {
3169 mydata.size = v2s32(
3170 mydata.invsize.X*imgsize.X,
3171 mydata.invsize.Y*imgsize.Y
3174 mydata.size = v2s32(
3175 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3176 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3180 DesiredRect = mydata.rect = core::rect<s32>(
3181 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3182 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3183 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3184 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3187 // Non-size[] form must consist only of text fields and
3188 // implicit "Proceed" button. Use default font, and
3189 // temporary form size which will be recalculated below.
3190 m_font = g_fontengine->getFont();
3191 m_btn_height = font_line_height(m_font) * 0.875;
3192 DesiredRect = core::rect<s32>(
3193 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3194 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3195 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3196 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3199 recalculateAbsolutePosition(false);
3200 mydata.basepos = getBasePos();
3201 m_tooltip_element->setOverrideFont(m_font);
3203 gui::IGUISkin *skin = Environment->getSkin();
3205 gui::IGUIFont *old_font = skin->getFont();
3206 skin->setFont(m_font);
3208 pos_offset = v2f32();
3210 // used for formspec versions < 3
3211 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3213 if (enable_prepends) {
3214 // Backup the coordinates so that prepends can use the coordinates of choice.
3215 bool rc_backup = mydata.real_coordinates;
3216 u16 version_backup = m_formspec_version;
3217 mydata.real_coordinates = false; // Old coordinates by default.
3219 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3220 for (const auto &element : prepend_elements)
3221 parseElement(&mydata, element);
3223 // legacy sorting for formspec versions < 3
3224 if (m_formspec_version >= 3)
3225 // prepends do not need to be reordered
3226 legacy_sort_start = Children.getLast();
3227 else if (version_backup >= 3)
3228 // only prepends elements have to be reordered
3229 legacySortElements(legacy_sort_start);
3231 m_formspec_version = version_backup;
3232 mydata.real_coordinates = rc_backup; // Restore coordinates
3235 for (; i< elements.size(); i++) {
3236 parseElement(&mydata, elements[i]);
3239 if (mydata.current_parent != this) {
3240 errorstream << "Invalid formspec string: scroll_container was never closed!"
3242 } else if (!container_stack.empty()) {
3243 errorstream << "Invalid formspec string: container was never closed!"
3247 // get the scrollbar elements for scroll_containers
3248 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3249 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3250 if (c.first == b.first.fname) {
3251 c.second->setScrollBar(b.second);
3257 // If there are fields without explicit size[], add a "Proceed"
3258 // button and adjust size to fit all the fields.
3259 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3260 mydata.rect = core::rect<s32>(
3261 mydata.screensize.X / 2 - 580 / 2,
3262 mydata.screensize.Y / 2 - 300 / 2,
3263 mydata.screensize.X / 2 + 580 / 2,
3264 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3267 DesiredRect = mydata.rect;
3268 recalculateAbsolutePosition(false);
3269 mydata.basepos = getBasePos();
3272 v2s32 pos = mydata.basepos;
3273 pos.Y = (mydata.simple_field_count + 2) * 60;
3275 v2s32 size = DesiredRect.getSize();
3276 mydata.rect = core::rect<s32>(
3277 size.X / 2 - 70, pos.Y,
3278 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3280 const wchar_t *text = wgettext("Proceed");
3281 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3286 // Set initial focus if parser didn't set it
3287 gui::IGUIElement *focused_element = Environment->getFocus();
3288 if (!focused_element
3289 || !isMyChild(focused_element)
3290 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3293 skin->setFont(old_font);
3296 if (m_formspec_version < 3)
3297 legacySortElements(legacy_sort_start);
3299 // Formname and regeneration setting
3300 if (!m_is_form_regenerated) {
3301 // Only set previous form name if we purposefully showed a new formspec
3302 m_last_formname = m_text_dst->m_formname;
3303 m_is_form_regenerated = true;
3307 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3310 Draw order for formspec_version <= 2:
3314 0 All other elements
3316 2 item_image, item_image_button
3321 if (from == Children.end())
3322 from = Children.begin();
3326 core::list<IGUIElement *>::Iterator to = Children.end();
3327 // 1: Copy into a sortable container
3328 std::vector<IGUIElement *> elements;
3329 for (auto it = from; it != to; ++it)
3330 elements.emplace_back(*it);
3332 // 2: Sort the container
3333 std::stable_sort(elements.begin(), elements.end(),
3334 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3335 const FieldSpec *spec_a = getSpecByID(a->getID());
3336 const FieldSpec *spec_b = getSpecByID(b->getID());
3337 return spec_a && spec_b &&
3338 spec_a->priority < spec_b->priority;
3341 // 3: Re-assign the pointers
3342 for (auto e : elements) {
3349 bool GUIFormSpecMenu::getAndroidUIInput()
3351 if (!hasAndroidUIInput())
3355 if (porting::getInputDialogState() == -1)
3358 std::string fieldname = m_jni_field_name;
3359 m_jni_field_name.clear();
3361 for (const FieldSpec &field : m_fields) {
3362 if (field.fname != fieldname)
3365 IGUIElement *element = getElementFromId(field.fid, true);
3367 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3370 std::string text = porting::getInputDialogValue();
3371 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3377 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3379 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3381 for (const GUIInventoryList *e : m_inventorylists) {
3382 s32 item_index = e->getItemIndexAtPos(p);
3383 if (item_index != -1)
3384 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3388 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3391 void GUIFormSpecMenu::drawSelectedItem()
3393 video::IVideoDriver* driver = Environment->getVideoDriver();
3395 if (!m_selected_item) {
3396 // reset rotation time
3397 drawItemStack(driver, m_font, ItemStack(),
3398 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3399 m_client, IT_ROT_DRAGGED);
3403 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3405 InventoryList *list = inv->getList(m_selected_item->listname);
3407 ItemStack stack = list->getItem(m_selected_item->i);
3408 stack.count = m_selected_amount;
3410 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3411 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3412 rect.constrainTo(driver->getViewPort());
3413 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3416 void GUIFormSpecMenu::drawMenu()
3419 const std::string &newform = m_form_src->getForm();
3420 if (newform != m_formspec_string) {
3421 m_formspec_string = newform;
3422 m_is_form_regenerated = false;
3423 regenerateGui(m_screensize_old);
3427 gui::IGUISkin* skin = Environment->getSkin();
3428 sanity_check(skin != NULL);
3429 gui::IGUIFont *old_font = skin->getFont();
3430 skin->setFont(m_font);
3432 m_hovered_item_tooltips.clear();
3434 updateSelectedItem();
3436 video::IVideoDriver* driver = Environment->getVideoDriver();
3439 Draw background color
3441 v2u32 screenSize = driver->getScreenSize();
3442 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3445 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3446 if (m_bgnonfullscreen)
3447 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3450 Draw rect_mode tooltip
3452 m_tooltip_element->setVisible(false);
3454 for (const auto &pair : m_tooltip_rects) {
3455 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3456 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3457 const std::wstring &text = pair.second.tooltip;
3458 if (!text.empty()) {
3459 showTooltip(text, pair.second.color, pair.second.bgcolor);
3468 for (gui::IGUIElement *e : m_backgrounds) {
3469 e->setVisible(true);
3471 e->setVisible(false);
3474 // Some elements are only visible while being drawn
3475 for (gui::IGUIElement *e : m_clickthrough_elements)
3476 e->setVisible(true);
3480 (This is where all the drawing happens.)
3482 gui::IGUIElement::draw();
3484 for (gui::IGUIElement *e : m_clickthrough_elements)
3485 e->setVisible(false);
3487 // Draw hovered item tooltips
3488 for (const std::string &tooltip : m_hovered_item_tooltips) {
3489 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3490 m_default_tooltip_bgcolor);
3493 if (m_hovered_item_tooltips.empty()) {
3494 // reset rotation time
3495 drawItemStack(driver, m_font, ItemStack(),
3496 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3497 NULL, m_client, IT_ROT_HOVERED);
3500 /* TODO find way to show tooltips on touchscreen */
3501 #ifndef HAVE_TOUCHSCREENGUI
3502 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3506 Draw fields/buttons tooltips and update the mouse cursor
3508 gui::IGUIElement *hovered =
3509 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3511 #ifndef HAVE_TOUCHSCREENGUI
3512 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3514 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3516 bool hovered_element_found = false;
3518 if (hovered != NULL) {
3520 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3521 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3524 s32 id = hovered->getID();
3527 m_old_tooltip_id = id;
3529 if (id == m_old_tooltip_id) {
3530 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3532 m_hovered_time = porting::getTimeMs();
3533 m_old_tooltip_id = id;
3537 // Find and update the current tooltip and cursor icon
3539 for (const FieldSpec &field : m_fields) {
3541 if (field.fid != id)
3544 if (delta >= m_tooltip_show_delay) {
3545 const std::wstring &text = m_tooltips[field.fname].tooltip;
3547 showTooltip(text, m_tooltips[field.fname].color,
3548 m_tooltips[field.fname].bgcolor);
3551 #ifndef HAVE_TOUCHSCREENGUI
3552 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3553 current_cursor_icon != field.fcursor_icon)
3554 cursor_control->setActiveIcon(field.fcursor_icon);
3557 hovered_element_found = true;
3564 if (!hovered_element_found) {
3565 // no element is hovered
3566 #ifndef HAVE_TOUCHSCREENGUI
3567 if (current_cursor_icon != ECI_NORMAL)
3568 cursor_control->setActiveIcon(ECI_NORMAL);
3572 m_tooltip_element->draw();
3575 Draw dragged item stack
3579 skin->setFont(old_font);
3583 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3584 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3586 EnrichedString ntext(text);
3587 ntext.setDefaultColor(color);
3588 ntext.setBackground(bgcolor);
3590 setStaticText(m_tooltip_element, ntext);
3592 // Tooltip size and offset
3593 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3594 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3596 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3597 int tooltip_offset_x = m_btn_height;
3598 int tooltip_offset_y = m_btn_height;
3600 tooltip_offset_x *= 3;
3601 tooltip_offset_y = 0;
3602 if (m_pointer.X > (s32)screenSize.X / 2)
3603 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3605 // Hide tooltip after ETIE_LEFT_UP
3606 if (m_pointer.X == 0)
3610 // Calculate and set the tooltip position
3611 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3612 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3613 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3614 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3615 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3616 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3618 m_tooltip_element->setRelativePosition(
3620 core::position2d<s32>(tooltip_x, tooltip_y),
3621 core::dimension2d<s32>(tooltip_width, tooltip_height)
3625 // Display the tooltip
3626 m_tooltip_element->setVisible(true);
3627 bringToFront(m_tooltip_element);
3630 void GUIFormSpecMenu::updateSelectedItem()
3632 verifySelectedItem();
3634 // If craftresult is nonempty and nothing else is selected, select it now.
3635 if (!m_selected_item) {
3636 for (const GUIInventoryList *e : m_inventorylists) {
3637 if (e->getListname() != "craftpreview")
3640 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3644 InventoryList *list = inv->getList("craftresult");
3646 if (!list || list->getSize() == 0)
3649 const ItemStack &item = list->getItem(0);
3653 // Grab selected item from the crafting result list
3654 m_selected_item = new GUIInventoryList::ItemSpec;
3655 m_selected_item->inventoryloc = e->getInventoryloc();
3656 m_selected_item->listname = "craftresult";
3657 m_selected_item->i = 0;
3658 m_selected_amount = item.count;
3659 m_selected_dragging = false;
3664 // If craftresult is selected, keep the whole stack selected
3665 if (m_selected_item && m_selected_item->listname == "craftresult")
3666 m_selected_amount = verifySelectedItem().count;
3669 ItemStack GUIFormSpecMenu::verifySelectedItem()
3671 // If the selected stack has become empty for some reason, deselect it.
3672 // If the selected stack has become inaccessible, deselect it.
3673 // If the selected stack has become smaller, adjust m_selected_amount.
3674 // Return the selected stack.
3676 if (m_selected_item) {
3677 if (m_selected_item->isValid()) {
3678 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3680 InventoryList *list = inv->getList(m_selected_item->listname);
3681 if (list && (u32) m_selected_item->i < list->getSize()) {
3682 ItemStack stack = list->getItem(m_selected_item->i);
3683 if (!m_selected_swap.empty()) {
3684 if (m_selected_swap.name == stack.name &&
3685 m_selected_swap.count == stack.count)
3686 m_selected_swap.clear();
3688 m_selected_amount = std::min(m_selected_amount, stack.count);
3697 // selection was not valid
3698 delete m_selected_item;
3699 m_selected_item = nullptr;
3700 m_selected_amount = 0;
3701 m_selected_dragging = false;
3706 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3712 if (quitmode == quit_mode_accept) {
3713 fields["quit"] = "true";
3716 if (quitmode == quit_mode_cancel) {
3717 fields["quit"] = "true";
3718 m_text_dst->gotText(fields);
3722 if (current_keys_pending.key_down) {
3723 fields["key_down"] = "true";
3724 current_keys_pending.key_down = false;
3727 if (current_keys_pending.key_up) {
3728 fields["key_up"] = "true";
3729 current_keys_pending.key_up = false;
3732 if (current_keys_pending.key_enter) {
3733 fields["key_enter"] = "true";
3734 current_keys_pending.key_enter = false;
3737 if (!current_field_enter_pending.empty()) {
3738 fields["key_enter_field"] = current_field_enter_pending;
3739 current_field_enter_pending = "";
3742 if (current_keys_pending.key_escape) {
3743 fields["key_escape"] = "true";
3744 current_keys_pending.key_escape = false;
3747 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3749 std::string name = s.fname;
3750 if (s.ftype == f_Button) {
3751 fields[name] = wide_to_utf8(s.flabel);
3752 } else if (s.ftype == f_Table) {
3753 GUITable *table = getTable(s.fname);
3755 fields[name] = table->checkEvent();
3757 } else if (s.ftype == f_DropDown) {
3758 // No dynamic cast possible due to some distributions shipped
3759 // without rtti support in Irrlicht
3760 IGUIElement *element = getElementFromId(s.fid, true);
3761 gui::IGUIComboBox *e = NULL;
3762 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3763 e = static_cast<gui::IGUIComboBox *>(element);
3765 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3766 << "field without dropdown element" << std::endl;
3769 s32 selected = e->getSelected();
3770 if (selected >= 0) {
3771 if (m_dropdown_index_event.find(s.fname) !=
3772 m_dropdown_index_event.end()) {
3773 fields[name] = std::to_string(selected + 1);
3775 std::vector<std::string> *dropdown_values =
3776 getDropDownValues(s.fname);
3777 if (dropdown_values && selected < (s32)dropdown_values->size())
3778 fields[name] = (*dropdown_values)[selected];
3781 } else if (s.ftype == f_TabHeader) {
3782 // No dynamic cast possible due to some distributions shipped
3783 // without rtti support in Irrlicht
3784 IGUIElement *element = getElementFromId(s.fid, true);
3785 gui::IGUITabControl *e = nullptr;
3786 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3787 e = static_cast<gui::IGUITabControl *>(element);
3791 std::stringstream ss;
3792 ss << (e->getActiveTab() +1);
3793 fields[name] = ss.str();
3795 } else if (s.ftype == f_CheckBox) {
3796 // No dynamic cast possible due to some distributions shipped
3797 // without rtti support in Irrlicht
3798 IGUIElement *element = getElementFromId(s.fid, true);
3799 gui::IGUICheckBox *e = nullptr;
3800 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3801 e = static_cast<gui::IGUICheckBox*>(element);
3806 fields[name] = "true";
3808 fields[name] = "false";
3810 } else if (s.ftype == f_ScrollBar) {
3811 // No dynamic cast possible due to some distributions shipped
3812 // without rtti support in Irrlicht
3813 IGUIElement *element = getElementFromId(s.fid, true);
3814 GUIScrollBar *e = nullptr;
3815 if (element && element->getType() == gui::EGUIET_ELEMENT)
3816 e = static_cast<GUIScrollBar *>(element);
3819 std::stringstream os;
3821 if (s.fdefault == L"Changed")
3822 fields[name] = "CHG:" + os.str();
3824 fields[name] = "VAL:" + os.str();
3826 } else if (s.ftype == f_AnimatedImage) {
3827 // No dynamic cast possible due to some distributions shipped
3828 // without rtti support in Irrlicht
3829 IGUIElement *element = getElementFromId(s.fid, true);
3830 GUIAnimatedImage *e = nullptr;
3831 if (element && element->getType() == gui::EGUIET_ELEMENT)
3832 e = static_cast<GUIAnimatedImage *>(element);
3835 fields[name] = std::to_string(e->getFrameIndex() + 1);
3837 IGUIElement *e = getElementFromId(s.fid, true);
3839 fields[name] = wide_to_utf8(e->getText());
3844 m_text_dst->gotText(fields);
3848 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3850 // The IGUITabControl renders visually using the skin's selected
3851 // font, which we override for the duration of form drawing,
3852 // but computes tab hotspots based on how it would have rendered
3853 // using the font that is selected at the time of button release.
3854 // To make these two consistent, temporarily override the skin's
3855 // font while the IGUITabControl is processing the event.
3856 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3857 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3858 s32 x = event.MouseInput.X;
3859 s32 y = event.MouseInput.Y;
3860 gui::IGUIElement *hovered =
3861 Environment->getRootGUIElement()->getElementFromPoint(
3862 core::position2d<s32>(x, y));
3863 if (hovered && isMyChild(hovered) &&
3864 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3865 gui::IGUISkin* skin = Environment->getSkin();
3866 sanity_check(skin != NULL);
3867 gui::IGUIFont *old_font = skin->getFont();
3868 skin->setFont(m_font);
3869 bool retval = hovered->OnEvent(event);
3870 skin->setFont(old_font);
3875 // Fix Esc/Return key being eaten by checkboxen and tables
3876 if (event.EventType == EET_KEY_INPUT_EVENT) {
3877 KeyPress kp(event.KeyInput);
3878 if (kp == EscapeKey || kp == CancelKey
3879 || kp == getKeySetting("keymap_inventory")
3880 || event.KeyInput.Key==KEY_RETURN) {
3881 gui::IGUIElement *focused = Environment->getFocus();
3882 if (focused && isMyChild(focused) &&
3883 (focused->getType() == gui::EGUIET_LIST_BOX ||
3884 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3885 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3886 event.KeyInput.Key != KEY_RETURN)) {
3892 // Mouse wheel and move events: send to hovered element instead of focused
3893 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3894 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3895 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3896 event.MouseInput.ButtonStates == 0))) {
3897 s32 x = event.MouseInput.X;
3898 s32 y = event.MouseInput.Y;
3899 gui::IGUIElement *hovered =
3900 Environment->getRootGUIElement()->getElementFromPoint(
3901 core::position2d<s32>(x, y));
3902 if (hovered && isMyChild(hovered)) {
3903 hovered->OnEvent(event);
3904 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3908 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3909 /* TODO add a check like:
3910 if (event.JoystickEvent != joystick_we_listen_for)
3913 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3915 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3917 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3919 acceptInput(quit_mode_accept);
3927 return GUIModalMenu::preprocessEvent(event);
3930 void GUIFormSpecMenu::tryClose()
3934 acceptInput(quit_mode_cancel);
3937 m_text_dst->gotText(L"MenuQuit");
3941 enum ButtonEventType : u8
3954 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3956 if (event.EventType==EET_KEY_INPUT_EVENT) {
3957 KeyPress kp(event.KeyInput);
3958 if (event.KeyInput.PressedDown && (
3959 (kp == EscapeKey) || (kp == CancelKey) ||
3960 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3965 if (m_client != NULL && event.KeyInput.PressedDown &&
3966 (kp == getKeySetting("keymap_screenshot"))) {
3967 m_client->makeScreenshot();
3970 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
3971 m_show_debug = !m_show_debug;
3973 if (event.KeyInput.PressedDown &&
3974 (event.KeyInput.Key==KEY_RETURN ||
3975 event.KeyInput.Key==KEY_UP ||
3976 event.KeyInput.Key==KEY_DOWN)
3978 switch (event.KeyInput.Key) {
3980 current_keys_pending.key_enter = true;
3983 current_keys_pending.key_up = true;
3986 current_keys_pending.key_down = true;
3990 //can't happen at all!
3991 FATAL_ERROR("Reached a source line that can't ever been reached");
3994 if (current_keys_pending.key_enter && m_allowclose) {
3995 acceptInput(quit_mode_accept);
4005 /* Mouse event other than movement, or crossing the border of inventory
4006 field while holding right mouse button
4008 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4009 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4010 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4011 event.MouseInput.isRightPressed() &&
4012 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4014 // Get selected item and hovered/clicked item (s)
4016 m_old_tooltip_id = -1;
4017 updateSelectedItem();
4018 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4020 Inventory *inv_selected = NULL;
4021 Inventory *inv_s = NULL;
4022 InventoryList *list_s = NULL;
4024 if (m_selected_item) {
4025 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4026 sanity_check(inv_selected);
4027 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4034 inv_s = m_invmgr->getInventory(s.inventoryloc);
4037 errorstream << "InventoryMenu: The selected inventory location "
4038 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4040 s.i = -1; // make it invalid again
4044 list_s = inv_s->getList(s.listname);
4045 if (list_s == NULL) {
4046 verbosestream << "InventoryMenu: The selected inventory list \""
4047 << s.listname << "\" does not exist" << std::endl;
4048 s.i = -1; // make it invalid again
4052 if ((u32)s.i >= list_s->getSize()) {
4053 infostream << "InventoryMenu: The selected inventory list \""
4054 << s.listname << "\" is too small (i=" << s.i << ", size="
4055 << list_s->getSize() << ")" << std::endl;
4056 s.i = -1; // make it invalid again
4060 s_count = list_s->getItem(s.i).count;
4063 bool identical = m_selected_item && s.isValid() &&
4064 (inv_selected == inv_s) &&
4065 (m_selected_item->listname == s.listname) &&
4066 (m_selected_item->i == s.i);
4068 ButtonEventType button = BET_LEFT;
4069 ButtonEventType updown = BET_OTHER;
4070 switch (event.MouseInput.Event) {
4071 case EMIE_LMOUSE_PRESSED_DOWN:
4072 button = BET_LEFT; updown = BET_DOWN;
4074 case EMIE_RMOUSE_PRESSED_DOWN:
4075 button = BET_RIGHT; updown = BET_DOWN;
4077 case EMIE_MMOUSE_PRESSED_DOWN:
4078 button = BET_MIDDLE; updown = BET_DOWN;
4080 case EMIE_MOUSE_WHEEL:
4081 button = (event.MouseInput.Wheel > 0) ?
4082 BET_WHEEL_UP : BET_WHEEL_DOWN;
4085 case EMIE_LMOUSE_LEFT_UP:
4086 button = BET_LEFT; updown = BET_UP;
4088 case EMIE_RMOUSE_LEFT_UP:
4089 button = BET_RIGHT; updown = BET_UP;
4091 case EMIE_MMOUSE_LEFT_UP:
4092 button = BET_MIDDLE; updown = BET_UP;
4094 case EMIE_MOUSE_MOVED:
4101 // Set this number to a positive value to generate a move action
4102 // from m_selected_item to s.
4103 u32 move_amount = 0;
4105 // Set this number to a positive value to generate a move action
4106 // from s to the next inventory ring.
4107 u32 shift_move_amount = 0;
4109 // Set this number to a positive value to generate a drop action
4110 // from m_selected_item.
4111 u32 drop_amount = 0;
4113 // Set this number to a positive value to generate a craft action at s.
4114 u32 craft_amount = 0;
4118 // Some mouse button has been pressed
4120 //infostream << "Mouse button " << button << " pressed at p=("
4121 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4124 m_selected_dragging = false;
4126 if (s.isValid() && s.listname == "craftpreview") {
4127 // Craft preview has been clicked: craft
4128 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4129 } else if (!m_selected_item) {
4130 if (s_count && button != BET_WHEEL_UP) {
4131 // Non-empty stack has been clicked: select or shift-move it
4132 m_selected_item = new GUIInventoryList::ItemSpec(s);
4135 if (button == BET_RIGHT)
4136 count = (s_count + 1) / 2;
4137 else if (button == BET_MIDDLE)
4138 count = MYMIN(s_count, 10);
4139 else if (button == BET_WHEEL_DOWN)
4144 if (!event.MouseInput.Shift) {
4145 // no shift: select item
4146 m_selected_amount = count;
4147 m_selected_dragging = button != BET_WHEEL_DOWN;
4148 m_auto_place = false;
4150 // shift pressed: move item, right click moves 1
4151 shift_move_amount = button == BET_RIGHT ? 1 : count;
4154 } else { // m_selected_item != NULL
4155 assert(m_selected_amount >= 1);
4158 // Clicked a slot: move
4159 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4161 else if (button == BET_MIDDLE)
4162 move_amount = MYMIN(m_selected_amount, 10);
4163 else if (button == BET_LEFT)
4164 move_amount = m_selected_amount;
4168 if (button == BET_WHEEL_DOWN) {
4169 if (m_selected_amount < s_count)
4170 ++m_selected_amount;
4172 if (move_amount >= m_selected_amount)
4173 m_selected_amount = 0;
4175 m_selected_amount -= move_amount;
4179 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4180 && button != BET_WHEEL_DOWN) {
4181 // Clicked outside of the window: drop
4182 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4184 else if (button == BET_MIDDLE)
4185 drop_amount = MYMIN(m_selected_amount, 10);
4187 drop_amount = m_selected_amount;
4192 // Some mouse button has been released
4194 //infostream<<"Mouse button "<<button<<" released at p=("
4195 // <<p.X<<","<<p.Y<<")"<<std::endl;
4197 if (m_selected_dragging && m_selected_item) {
4200 // Dragged to different slot: move all selected
4201 move_amount = m_selected_amount;
4203 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4204 // Dragged outside of window: drop all selected
4205 drop_amount = m_selected_amount;
4209 m_selected_dragging = false;
4210 // Keep track of whether the mouse button be released
4211 // One click is drag without dropping. Click + release
4212 // + click changes to drop item when moved mode
4213 if (m_selected_item)
4214 m_auto_place = true;
4217 // Mouse has been moved and rmb is down and mouse pointer just
4218 // entered a new inventory field (checked in the entry-if, this
4219 // is the only action here that is generated by mouse movement)
4220 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4222 // TODO: middle mouse to move 10 items might be handy
4224 // Only move an item if the destination slot is empty
4225 // or contains the same item type as what is going to be
4227 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4228 InventoryList *list_to = list_s;
4229 assert(list_from && list_to);
4230 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4231 ItemStack stack_to = list_to->getItem(s.i);
4232 if (stack_to.empty() || stack_to.name == stack_from.name)
4241 // Possibly send inventory action to server
4242 if (move_amount > 0) {
4243 // Send IAction::Move
4245 assert(m_selected_item && m_selected_item->isValid());
4246 assert(s.isValid());
4248 assert(inv_selected && inv_s);
4249 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4250 InventoryList *list_to = list_s;
4251 assert(list_from && list_to);
4252 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4253 ItemStack stack_to = list_to->getItem(s.i);
4255 // Check how many items can be moved
4256 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4257 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4259 // If source stack cannot be added to destination stack at all,
4261 if (leftover.count == stack_from.count &&
4262 leftover.name == stack_from.name) {
4264 if (m_selected_swap.empty()) {
4265 m_selected_amount = stack_to.count;
4266 m_selected_dragging = false;
4268 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4269 // Skip next validation checks due async inventory calls
4270 m_selected_swap = stack_to;
4275 // Source stack goes fully into destination stack
4276 else if (leftover.empty()) {
4277 m_selected_amount -= move_amount;
4279 // Source stack goes partly into destination stack
4281 move_amount -= leftover.count;
4282 m_selected_amount -= move_amount;
4286 infostream << "Handing IAction::Move to manager" << std::endl;
4287 IMoveAction *a = new IMoveAction();
4288 a->count = move_amount;
4289 a->from_inv = m_selected_item->inventoryloc;
4290 a->from_list = m_selected_item->listname;
4291 a->from_i = m_selected_item->i;
4292 a->to_inv = s.inventoryloc;
4293 a->to_list = s.listname;
4295 m_invmgr->inventoryAction(a);
4297 } else if (shift_move_amount > 0) {
4298 u32 mis = m_inventory_rings.size();
4300 for (; i < mis; i++) {
4301 const ListRingSpec &sp = m_inventory_rings[i];
4302 if (sp.inventoryloc == s.inventoryloc
4303 && sp.listname == s.listname)
4307 if (i >= mis) // if not found
4309 u32 to_inv_ind = (i + 1) % mis;
4310 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4311 InventoryList *list_from = list_s;
4314 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4317 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4320 ItemStack stack_from = list_from->getItem(s.i);
4321 assert(shift_move_amount <= stack_from.count);
4323 infostream << "Handing IAction::Move to manager" << std::endl;
4324 IMoveAction *a = new IMoveAction();
4325 a->count = shift_move_amount;
4326 a->from_inv = s.inventoryloc;
4327 a->from_list = s.listname;
4329 a->to_inv = to_inv_sp.inventoryloc;
4330 a->to_list = to_inv_sp.listname;
4331 a->move_somewhere = true;
4332 m_invmgr->inventoryAction(a);
4334 } else if (drop_amount > 0) {
4335 // Send IAction::Drop
4337 assert(m_selected_item && m_selected_item->isValid());
4338 assert(inv_selected);
4339 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4341 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4343 // Check how many items can be dropped
4344 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4345 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4346 m_selected_amount -= drop_amount;
4348 infostream << "Handing IAction::Drop to manager" << std::endl;
4349 IDropAction *a = new IDropAction();
4350 a->count = drop_amount;
4351 a->from_inv = m_selected_item->inventoryloc;
4352 a->from_list = m_selected_item->listname;
4353 a->from_i = m_selected_item->i;
4354 m_invmgr->inventoryAction(a);
4355 } else if (craft_amount > 0) {
4356 assert(s.isValid());
4358 // if there are no items selected or the selected item
4359 // belongs to craftresult list, proceed with crafting
4360 if (!m_selected_item ||
4361 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4365 // Send IACTION_CRAFT
4366 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4367 ICraftAction *a = new ICraftAction();
4368 a->count = craft_amount;
4369 a->craft_inv = s.inventoryloc;
4370 m_invmgr->inventoryAction(a);
4374 // If m_selected_amount has been decreased to zero, deselect
4375 if (m_selected_amount == 0) {
4376 m_selected_swap.clear();
4377 delete m_selected_item;
4378 m_selected_item = nullptr;
4379 m_selected_amount = 0;
4380 m_selected_dragging = false;
4382 m_old_pointer = m_pointer;
4385 if (event.EventType == EET_GUI_EVENT) {
4386 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4388 // find the element that was clicked
4389 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4390 if ((s.ftype == f_TabHeader) &&
4391 (s.fid == event.GUIEvent.Caller->getID())) {
4399 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4401 if (!canTakeFocus(event.GUIEvent.Element)) {
4402 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4404 // Returning true disables focus change
4408 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4409 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4410 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4411 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4412 s32 caller_id = event.GUIEvent.Caller->getID();
4414 if (caller_id == 257) {
4416 acceptInput(quit_mode_accept);
4420 m_text_dst->gotText(L"ExitButton");
4422 // quitMenu deallocates menu
4426 // find the element that was clicked
4427 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4428 // if its a button, set the send field so
4429 // lua knows which button was pressed
4431 if (caller_id != s.fid)
4434 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4438 acceptInput(quit_mode_accept);
4441 m_text_dst->gotText(L"ExitButton");
4446 acceptInput(quit_mode_no);
4450 } else if (s.ftype == f_DropDown) {
4451 // only send the changed dropdown
4452 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4453 if (s2.ftype == f_DropDown) {
4458 acceptInput(quit_mode_no);
4460 // revert configuration to make sure dropdowns are sent on
4461 // regular button click
4462 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4463 if (s2.ftype == f_DropDown) {
4468 } else if (s.ftype == f_ScrollBar) {
4469 s.fdefault = L"Changed";
4470 acceptInput(quit_mode_no);
4472 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4480 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4481 // move scroll_containers
4482 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4483 c.second->onScrollEvent(event.GUIEvent.Caller);
4486 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4487 if (event.GUIEvent.Caller->getID() > 257) {
4488 bool close_on_enter = true;
4489 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4490 if (s.ftype == f_Unknown &&
4491 s.fid == event.GUIEvent.Caller->getID()) {
4492 current_field_enter_pending = s.fname;
4493 std::unordered_map<std::string, bool>::const_iterator it =
4494 field_close_on_enter.find(s.fname);
4495 if (it != field_close_on_enter.end())
4496 close_on_enter = (*it).second;
4502 if (m_allowclose && close_on_enter) {
4503 current_keys_pending.key_enter = true;
4504 acceptInput(quit_mode_accept);
4507 current_keys_pending.key_enter = true;
4510 // quitMenu deallocates menu
4515 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4516 int current_id = event.GUIEvent.Caller->getID();
4517 if (current_id > 257) {
4518 // find the element that was clicked
4519 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4520 // if it's a table, set the send field
4521 // so lua knows which table was changed
4522 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4533 return Parent ? Parent->OnEvent(event) : false;
4537 * get name of element by element id
4538 * @param id of element
4539 * @return name string or empty string
4541 std::string GUIFormSpecMenu::getNameByID(s32 id)
4543 for (FieldSpec &spec : m_fields) {
4551 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4553 for (FieldSpec &spec : m_fields) {
4561 * get label of element by id
4562 * @param id of element
4563 * @return label string or empty string
4565 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4567 for (FieldSpec &spec : m_fields) {
4574 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4575 const std::string &name, const std::string &parent_type) {
4576 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4579 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4580 const std::string &type, const std::string &name, const std::string &parent_type)
4582 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4584 auto it = theme_by_type.find("*");
4585 if (it != theme_by_type.end()) {
4586 for (const StyleSpec &spec : it->second)
4587 ret[(u32)spec.getState()] |= spec;
4590 it = theme_by_name.find("*");
4591 if (it != theme_by_name.end()) {
4592 for (const StyleSpec &spec : it->second)
4593 ret[(u32)spec.getState()] |= spec;
4596 if (!parent_type.empty()) {
4597 it = theme_by_type.find(parent_type);
4598 if (it != theme_by_type.end()) {
4599 for (const StyleSpec &spec : it->second)
4600 ret[(u32)spec.getState()] |= spec;
4604 it = theme_by_type.find(type);
4605 if (it != theme_by_type.end()) {
4606 for (const StyleSpec &spec : it->second)
4607 ret[(u32)spec.getState()] |= spec;
4610 it = theme_by_name.find(name);
4611 if (it != theme_by_name.end()) {
4612 for (const StyleSpec &spec : it->second)
4613 ret[(u32)spec.getState()] |= spec;