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));
1229 m_tables.emplace_back(spec, e);
1230 m_fields.push_back(spec);
1233 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1236 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1238 std::vector<std::string> parts = split(element,';');
1240 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1241 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1243 std::vector<std::string> v_pos = split(parts[0],',');
1244 std::vector<std::string> v_geom = split(parts[1],',');
1245 std::string name = parts[2];
1246 std::vector<std::string> items = split(parts[3],',');
1247 std::string str_initial_selection;
1248 std::string str_transparent = "false";
1250 if (parts.size() >= 5)
1251 str_initial_selection = parts[4];
1253 if (parts.size() >= 6)
1254 str_transparent = parts[5];
1256 MY_CHECKPOS("textlist",0);
1257 MY_CHECKGEOM("textlist",1);
1262 if (data->real_coordinates) {
1263 pos = getRealCoordinateBasePos(v_pos);
1264 geom = getRealCoordinateGeometry(v_geom);
1266 pos = getElementBasePos(&v_pos);
1267 geom.X = stof(v_geom[0]) * spacing.X;
1268 geom.Y = stof(v_geom[1]) * spacing.Y;
1271 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1277 258 + m_fields.size()
1280 spec.ftype = f_Table;
1282 for (std::string &item : items) {
1283 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1286 //now really show list
1287 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1290 if (spec.fname == m_focused_element) {
1291 Environment->setFocus(e);
1294 e->setTextList(items, is_yes(str_transparent));
1296 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1297 e->setDynamicData(data->table_dyndata[name]);
1300 if (!str_initial_selection.empty() && str_initial_selection != "0")
1301 e->setSelected(stoi(str_initial_selection));
1303 auto style = getDefaultStyleForElement("textlist", name);
1304 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1306 m_tables.emplace_back(spec, e);
1307 m_fields.push_back(spec);
1310 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1313 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1315 std::vector<std::string> parts = split(element, ';');
1317 if (parts.size() == 5 || parts.size() == 6 ||
1318 (parts.size() > 6 && m_formspec_version > FORMSPEC_API_VERSION))
1320 std::vector<std::string> v_pos = split(parts[0], ',');
1321 std::string name = parts[2];
1322 std::vector<std::string> items = split(parts[3], ',');
1323 std::string str_initial_selection = parts[4];
1325 if (parts.size() >= 6 && is_yes(parts[5]))
1326 m_dropdown_index_event[name] = true;
1328 MY_CHECKPOS("dropdown",0);
1332 core::rect<s32> rect;
1334 if (data->real_coordinates) {
1335 std::vector<std::string> v_geom = split(parts[1],',');
1337 if (v_geom.size() == 1)
1338 v_geom.emplace_back("1");
1340 MY_CHECKGEOM("dropdown",1);
1342 pos = getRealCoordinateBasePos(v_pos);
1343 geom = getRealCoordinateGeometry(v_geom);
1344 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1346 pos = getElementBasePos(&v_pos);
1348 s32 width = stof(parts[1]) * spacing.Y;
1350 rect = core::rect<s32>(pos.X, pos.Y,
1351 pos.X + width, pos.Y + (m_btn_height * 2));
1358 258 + m_fields.size()
1361 spec.ftype = f_DropDown;
1364 //now really show list
1365 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1368 if (spec.fname == m_focused_element) {
1369 Environment->setFocus(e);
1372 for (const std::string &item : items) {
1373 e->addItem(unescape_translate(unescape_string(
1374 utf8_to_wide(item))).c_str());
1377 if (!str_initial_selection.empty())
1378 e->setSelected(stoi(str_initial_selection)-1);
1380 auto style = getDefaultStyleForElement("dropdown", name);
1381 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1383 m_fields.push_back(spec);
1385 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1386 std::vector<std::string> &values = m_dropdowns.back().second;
1387 for (const std::string &item : items) {
1388 values.push_back(unescape_string(item));
1393 errorstream << "Invalid dropdown element(" << parts.size() << "): '" << element
1394 << "'" << std::endl;
1397 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1399 std::vector<std::string> parts = split(element,';');
1400 if (parts.size() == 2 ||
1401 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1402 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1406 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1408 std::vector<std::string> parts = split(element,';');
1410 if (parts.size() == 4 ||
1411 (parts.size() > 4 && m_formspec_version > FORMSPEC_API_VERSION))
1413 std::vector<std::string> v_pos = split(parts[0],',');
1414 std::vector<std::string> v_geom = split(parts[1],',');
1415 std::string name = parts[2];
1416 std::string label = parts[3];
1418 MY_CHECKPOS("pwdfield",0);
1419 MY_CHECKGEOM("pwdfield",1);
1424 if (data->real_coordinates) {
1425 pos = getRealCoordinateBasePos(v_pos);
1426 geom = getRealCoordinateGeometry(v_geom);
1428 pos = getElementBasePos(&v_pos);
1431 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1433 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1434 pos.Y -= m_btn_height;
1435 geom.Y = m_btn_height*2;
1438 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1440 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1446 258 + m_fields.size(),
1452 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1453 data->current_parent, spec.fid);
1455 if (spec.fname == m_focused_element) {
1456 Environment->setFocus(e);
1459 if (label.length() >= 1) {
1460 int font_height = g_fontengine->getTextHeight();
1461 rect.UpperLeftCorner.Y -= font_height;
1462 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1463 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1464 data->current_parent, 0);
1467 e->setPasswordBox(true,L'*');
1469 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1470 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1471 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1472 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1473 e->setOverrideFont(style.getFont());
1476 evt.EventType = EET_KEY_INPUT_EVENT;
1477 evt.KeyInput.Key = KEY_END;
1478 evt.KeyInput.Char = 0;
1479 evt.KeyInput.Control = false;
1480 evt.KeyInput.Shift = false;
1481 evt.KeyInput.PressedDown = true;
1484 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1485 // warning referring to field_close_on_enter[]!
1487 m_fields.push_back(spec);
1490 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1493 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1494 core::rect<s32> &rect, bool is_multiline)
1496 bool is_editable = !spec.fname.empty();
1497 if (!is_editable && !is_multiline) {
1498 // spec field id to 0, this stops submit searching for a value that isn't there
1499 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1500 data->current_parent, 0);
1506 } else if (is_multiline &&
1507 spec.fdefault.empty() && !spec.flabel.empty()) {
1508 // Multiline textareas: swap default and label for backwards compat
1509 spec.flabel.swap(spec.fdefault);
1512 gui::IGUIEditBox *e = nullptr;
1513 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1514 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1516 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1517 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1518 data->current_parent, spec.fid, rect, is_editable, is_multiline);
1521 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1522 data->current_parent, spec.fid, rect, is_editable, true);
1523 } else if (is_editable) {
1524 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1525 data->current_parent, spec.fid);
1530 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1533 if (is_editable && spec.fname == m_focused_element)
1534 Environment->setFocus(e);
1537 e->setMultiLine(true);
1538 e->setWordWrap(true);
1539 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1542 evt.EventType = EET_KEY_INPUT_EVENT;
1543 evt.KeyInput.Key = KEY_END;
1544 evt.KeyInput.Char = 0;
1545 evt.KeyInput.Control = 0;
1546 evt.KeyInput.Shift = 0;
1547 evt.KeyInput.PressedDown = true;
1551 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1552 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1553 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1554 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1555 e->setDrawBackground(false);
1557 e->setOverrideFont(style.getFont());
1562 if (!spec.flabel.empty()) {
1563 int font_height = g_fontengine->getTextHeight();
1564 rect.UpperLeftCorner.Y -= font_height;
1565 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1566 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1567 rect, false, true, data->current_parent, 0);
1570 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1574 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1575 std::vector<std::string> &parts)
1577 std::string name = parts[0];
1578 std::string label = parts[1];
1579 std::string default_val = parts[2];
1581 core::rect<s32> rect;
1583 if (data->explicit_size)
1584 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1586 v2s32 pos = getElementBasePos(nullptr);
1587 pos.Y = (data->simple_field_count + 2) * 60;
1588 v2s32 size = DesiredRect.getSize();
1590 rect = core::rect<s32>(
1591 size.X / 2 - 150, pos.Y,
1592 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1597 default_val = m_form_src->resolveText(default_val);
1600 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1605 utf8_to_wide(unescape_string(default_val)),
1606 258 + m_fields.size(),
1611 createTextField(data, spec, rect, false);
1613 m_fields.push_back(spec);
1615 data->simple_field_count++;
1618 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1619 const std::string &type)
1621 std::vector<std::string> v_pos = split(parts[0],',');
1622 std::vector<std::string> v_geom = split(parts[1],',');
1623 std::string name = parts[2];
1624 std::string label = parts[3];
1625 std::string default_val = parts[4];
1627 MY_CHECKPOS(type,0);
1628 MY_CHECKGEOM(type,1);
1633 if (data->real_coordinates) {
1634 pos = getRealCoordinateBasePos(v_pos);
1635 geom = getRealCoordinateGeometry(v_geom);
1637 pos = getElementBasePos(&v_pos);
1640 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1642 if (type == "textarea")
1644 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1645 pos.Y += m_btn_height;
1649 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1650 pos.Y -= m_btn_height;
1651 geom.Y = m_btn_height*2;
1655 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1657 if(!data->explicit_size)
1658 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1661 default_val = m_form_src->resolveText(default_val);
1664 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1669 utf8_to_wide(unescape_string(default_val)),
1670 258 + m_fields.size(),
1675 createTextField(data, spec, rect, type == "textarea");
1677 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1678 // warning referring to field_close_on_enter[]!
1680 m_fields.push_back(spec);
1683 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1684 const std::string &type)
1686 std::vector<std::string> parts = split(element,';');
1688 if (parts.size() == 3 || parts.size() == 4) {
1689 parseSimpleField(data,parts);
1693 if ((parts.size() == 5) ||
1694 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1696 parseTextArea(data,parts,type);
1699 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1702 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1704 std::vector<std::string> parts = split(element, ';');
1706 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1707 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1711 std::vector<std::string> v_pos = split(parts[0], ',');
1712 std::vector<std::string> v_geom = split(parts[1], ',');
1713 std::string name = parts[2];
1714 std::string text = parts[3];
1716 MY_CHECKPOS("hypertext", 0);
1717 MY_CHECKGEOM("hypertext", 1);
1722 if (data->real_coordinates) {
1723 pos = getRealCoordinateBasePos(v_pos);
1724 geom = getRealCoordinateGeometry(v_geom);
1726 pos = getElementBasePos(&v_pos);
1729 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1730 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1731 pos.Y += m_btn_height;
1734 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1737 text = m_form_src->resolveText(text);
1741 utf8_to_wide(unescape_string(text)),
1743 258 + m_fields.size()
1746 spec.ftype = f_HyperText;
1747 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1748 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1751 m_fields.push_back(spec);
1754 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1756 std::vector<std::string> parts = split(element,';');
1758 if ((parts.size() == 2) ||
1759 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1761 std::vector<std::string> v_pos = split(parts[0],',');
1762 std::string text = parts[1];
1764 MY_CHECKPOS("label",0);
1766 if(!data->explicit_size)
1767 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1769 std::vector<std::string> lines = split(text, '\n');
1771 auto style = getDefaultStyleForElement("label", "");
1772 gui::IGUIFont *font = style.getFont();
1776 for (unsigned int i = 0; i != lines.size(); i++) {
1777 std::wstring wlabel_colors = translate_string(
1778 utf8_to_wide(unescape_string(lines[i])));
1779 // Without color escapes to get the font dimensions
1780 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1782 core::rect<s32> rect;
1784 if (data->real_coordinates) {
1785 // Lines are spaced at the distance of 1/2 imgsize.
1786 // This alows lines that line up with the new elements
1787 // easily without sacrificing good line distance. If
1788 // it was one whole imgsize, it would have too much
1790 v2s32 pos = getRealCoordinateBasePos(v_pos);
1792 // Labels are positioned by their center, not their top.
1793 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1795 rect = core::rect<s32>(
1797 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1801 // Lines are spaced at the nominal distance of
1802 // 2/5 inventory slot, even if the font doesn't
1803 // quite match that. This provides consistent
1804 // form layout, at the expense of sometimes
1805 // having sub-optimal spacing for the font.
1806 // We multiply by 2 and then divide by 5, rather
1807 // than multiply by 0.4, to get exact results
1808 // in the integer cases: 0.4 is not exactly
1809 // representable in binary floating point.
1811 v2s32 pos = getElementBasePos(nullptr);
1812 pos.X += stof(v_pos[0]) * spacing.X;
1813 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1815 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1817 rect = core::rect<s32>(
1818 pos.X, pos.Y - m_btn_height,
1819 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1820 pos.Y + m_btn_height);
1827 258 + m_fields.size(),
1830 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1831 spec.flabel.c_str(), rect, false, false, data->current_parent,
1833 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1835 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1836 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1837 e->setOverrideFont(font);
1839 m_fields.push_back(spec);
1841 // labels should let events through
1843 m_clickthrough_elements.push_back(e);
1848 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1849 << "'" << std::endl;
1852 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1854 std::vector<std::string> parts = split(element,';');
1856 if ((parts.size() == 2) ||
1857 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1859 std::vector<std::string> v_pos = split(parts[0],',');
1860 std::wstring text = unescape_translate(
1861 unescape_string(utf8_to_wide(parts[1])));
1863 MY_CHECKPOS("vertlabel",1);
1865 auto style = getDefaultStyleForElement("vertlabel", "", "label");
1866 gui::IGUIFont *font = style.getFont();
1871 core::rect<s32> rect;
1873 if (data->real_coordinates) {
1874 pos = getRealCoordinateBasePos(v_pos);
1876 // Vertlabels are positioned by center, not left.
1877 pos.X -= imgsize.X / 2;
1879 // We use text.length + 1 because without it, the rect
1880 // isn't quite tall enough and cuts off the text.
1881 rect = core::rect<s32>(pos.X, pos.Y,
1883 pos.Y + font_line_height(font) *
1884 (text.length() + 1));
1887 pos = getElementBasePos(&v_pos);
1889 // As above, the length must be one longer. The width of
1890 // the rect (15 pixels) seems rather arbitrary, but
1891 // changing it might break something.
1892 rect = core::rect<s32>(
1893 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1895 font_line_height(font) *
1896 (text.length() + 1) +
1897 ((imgsize.Y/2) - m_btn_height));
1900 if(!data->explicit_size)
1901 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1905 for (wchar_t i : text) {
1914 258 + m_fields.size()
1916 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1917 rect, false, false, data->current_parent, spec.fid);
1918 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1920 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1921 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1922 e->setOverrideFont(font);
1924 m_fields.push_back(spec);
1926 // vertlabels should let events through
1928 m_clickthrough_elements.push_back(e);
1931 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1934 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1935 const std::string &type)
1937 std::vector<std::string> parts = split(element,';');
1939 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1940 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1942 std::vector<std::string> v_pos = split(parts[0],',');
1943 std::vector<std::string> v_geom = split(parts[1],',');
1944 std::string image_name = parts[2];
1945 std::string name = parts[3];
1946 std::string label = parts[4];
1948 MY_CHECKPOS("imagebutton",0);
1949 MY_CHECKGEOM("imagebutton",1);
1951 std::string pressed_image_name;
1953 if (parts.size() >= 8) {
1954 pressed_image_name = parts[7];
1960 if (data->real_coordinates) {
1961 pos = getRealCoordinateBasePos(v_pos);
1962 geom = getRealCoordinateGeometry(v_geom);
1964 pos = getElementBasePos(&v_pos);
1965 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1966 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1969 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1972 if (!data->explicit_size)
1973 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1975 image_name = unescape_string(image_name);
1976 pressed_image_name = unescape_string(pressed_image_name);
1978 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1983 utf8_to_wide(image_name),
1984 258 + m_fields.size()
1986 spec.ftype = f_Button;
1987 if (type == "image_button_exit")
1988 spec.is_exit = true;
1990 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1991 data->current_parent, spec.fid, spec.flabel.c_str());
1993 if (spec.fname == m_focused_element) {
1994 Environment->setFocus(e);
1997 auto style = getStyleForElement("image_button", spec.fname);
1999 // Override style properties with values specified directly in the element
2000 if (!image_name.empty())
2001 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
2003 if (!pressed_image_name.empty())
2004 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
2006 if (parts.size() >= 7) {
2007 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
2008 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
2011 e->setStyles(style);
2012 e->setScaleImage(true);
2014 m_fields.push_back(spec);
2018 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2021 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2023 std::vector<std::string> parts = split(element, ';');
2025 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
2026 data->real_coordinates) || ((parts.size() > 6) &&
2027 (m_formspec_version > FORMSPEC_API_VERSION)))
2029 std::vector<std::string> v_pos = split(parts[0],',');
2031 // If we're using real coordinates, add an extra field for height.
2032 // Width is not here because tabs are the width of the text, and
2033 // there's no reason to change that.
2035 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2036 bool auto_width = true;
2037 if (parts.size() == 7) {
2040 v_geom = split(parts[1], ',');
2041 if (v_geom.size() == 1)
2042 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2047 std::string name = parts[i+1];
2048 std::vector<std::string> buttons = split(parts[i+2], ',');
2049 std::string str_index = parts[i+3];
2050 bool show_background = true;
2051 bool show_border = true;
2052 int tab_index = stoi(str_index) - 1;
2054 MY_CHECKPOS("tabheader", 0);
2056 if (parts.size() == 6 + i) {
2057 if (parts[4+i] == "true")
2058 show_background = false;
2059 if (parts[5+i] == "false")
2060 show_border = false;
2067 258 + m_fields.size()
2070 spec.ftype = f_TabHeader;
2075 if (data->real_coordinates) {
2076 pos = getRealCoordinateBasePos(v_pos);
2078 geom = getRealCoordinateGeometry(v_geom);
2079 // Set default height
2080 if (parts.size() <= 6)
2081 geom.Y = m_btn_height * 2;
2082 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2084 geom.X = DesiredRect.getWidth(); // Set automatic width
2086 MY_CHECKGEOM("tabheader", 1);
2088 v2f32 pos_f = pos_offset * spacing;
2089 pos_f.X += stof(v_pos[0]) * spacing.X;
2090 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2091 pos = v2s32(pos_f.X, pos_f.Y);
2093 geom.Y = m_btn_height * 2;
2094 geom.X = DesiredRect.getWidth();
2097 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2100 gui::IGUITabControl *e = Environment->addTabControl(rect,
2101 data->current_parent, show_background, show_border, spec.fid);
2102 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2103 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2104 e->setTabHeight(geom.Y);
2106 auto style = getDefaultStyleForElement("tabheader", name);
2107 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2109 for (const std::string &button : buttons) {
2110 auto tab = e->addTab(unescape_translate(unescape_string(
2111 utf8_to_wide(button))).c_str(), -1);
2112 if (style.isNotDefault(StyleSpec::BGCOLOR))
2113 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2115 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2118 if ((tab_index >= 0) &&
2119 (buttons.size() < INT_MAX) &&
2120 (tab_index < (int) buttons.size()))
2121 e->setActiveTab(tab_index);
2123 m_fields.push_back(spec);
2126 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2127 << element << "'" << std::endl;
2130 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2132 if (m_client == 0) {
2133 warningstream << "invalid use of item_image_button with m_client==0"
2138 std::vector<std::string> parts = split(element,';');
2140 if ((parts.size() == 5) ||
2141 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2143 std::vector<std::string> v_pos = split(parts[0],',');
2144 std::vector<std::string> v_geom = split(parts[1],',');
2145 std::string item_name = parts[2];
2146 std::string name = parts[3];
2147 std::string label = parts[4];
2149 label = unescape_string(label);
2150 item_name = unescape_string(item_name);
2152 MY_CHECKPOS("itemimagebutton",0);
2153 MY_CHECKGEOM("itemimagebutton",1);
2158 if (data->real_coordinates) {
2159 pos = getRealCoordinateBasePos(v_pos);
2160 geom = getRealCoordinateGeometry(v_geom);
2162 pos = getElementBasePos(&v_pos);
2163 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2164 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2167 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2169 if(!data->explicit_size)
2170 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2172 IItemDefManager *idef = m_client->idef();
2174 item.deSerialize(item_name, idef);
2177 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2178 m_default_tooltip_bgcolor,
2179 m_default_tooltip_color);
2181 // the spec for the button
2184 utf8_to_wide(label),
2185 utf8_to_wide(item_name),
2186 258 + m_fields.size(),
2190 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2191 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2192 item_name, m_client);
2194 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2195 e_btn->setStyles(style);
2197 if (spec_btn.fname == m_focused_element) {
2198 Environment->setFocus(e_btn);
2201 spec_btn.ftype = f_Button;
2202 rect += data->basepos-padding;
2203 spec_btn.rect = rect;
2204 m_fields.push_back(spec_btn);
2207 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2210 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2212 std::vector<std::string> parts = split(element,';');
2214 if ((parts.size() == 3) ||
2215 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2217 std::vector<std::string> v_pos = split(parts[0],',');
2218 std::vector<std::string> v_geom = split(parts[1],',');
2220 MY_CHECKPOS("box",0);
2221 MY_CHECKGEOM("box",1);
2226 if (data->real_coordinates) {
2227 pos = getRealCoordinateBasePos(v_pos);
2228 geom = getRealCoordinateGeometry(v_geom);
2230 pos = getElementBasePos(&v_pos);
2231 geom.X = stof(v_geom[0]) * spacing.X;
2232 geom.Y = stof(v_geom[1]) * spacing.Y;
2235 video::SColor tmp_color;
2237 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2242 258 + m_fields.size(),
2247 core::rect<s32> rect(pos, pos + geom);
2249 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid,
2252 auto style = getDefaultStyleForElement("box", spec.fname);
2253 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2257 m_fields.push_back(spec);
2260 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2264 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2267 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2269 std::vector<std::string> parts = split(element,';');
2270 const u32 parameter_count = parts.size();
2272 if ((parameter_count > 2 && m_formspec_version < 3) ||
2273 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2274 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2275 << element << "'" << std::endl;
2280 if (parameter_count >= 1 && parts[0] != "")
2281 parseColorString(parts[0], m_bgcolor, false);
2284 if (parameter_count >= 2) {
2285 if (parts[1] == "both") {
2286 m_bgnonfullscreen = true;
2287 m_bgfullscreen = true;
2288 } else if (parts[1] == "neither") {
2289 m_bgnonfullscreen = false;
2290 m_bgfullscreen = false;
2291 } else if (parts[1] != "" || m_formspec_version < 3) {
2292 m_bgfullscreen = is_yes(parts[1]);
2293 m_bgnonfullscreen = !m_bgfullscreen;
2298 if (parameter_count >= 3 && parts[2] != "")
2299 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2302 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2304 std::vector<std::string> parts = split(element,';');
2306 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2307 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2309 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2310 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2312 if (parts.size() >= 3) {
2313 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2315 data->inventorylist_options.slotborder = true;
2318 if (parts.size() == 5) {
2319 video::SColor tmp_color;
2321 if (parseColorString(parts[3], tmp_color, false))
2322 m_default_tooltip_bgcolor = tmp_color;
2323 if (parseColorString(parts[4], tmp_color, false))
2324 m_default_tooltip_color = tmp_color;
2327 // update all already parsed inventorylists
2328 for (GUIInventoryList *e : m_inventorylists) {
2329 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2330 data->inventorylist_options.slotbg_h);
2331 e->setSlotBorders(data->inventorylist_options.slotborder,
2332 data->inventorylist_options.slotbordercolor);
2336 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2339 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2341 std::vector<std::string> parts = split(element,';');
2342 if (parts.size() < 2) {
2343 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2344 << element << "'" << std::endl;
2348 // Get mode and check size
2349 bool rect_mode = parts[0].find(',') != std::string::npos;
2350 size_t base_size = rect_mode ? 3 : 2;
2351 if (parts.size() != base_size && parts.size() != base_size + 2) {
2352 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2353 << element << "'" << std::endl;
2358 video::SColor bgcolor = m_default_tooltip_bgcolor;
2359 video::SColor color = m_default_tooltip_color;
2360 if (parts.size() == base_size + 2 &&
2361 (!parseColorString(parts[base_size], bgcolor, false) ||
2362 !parseColorString(parts[base_size + 1], color, false))) {
2363 errorstream << "Invalid color in tooltip element(" << parts.size()
2364 << "): '" << element << "'" << std::endl;
2368 // Make tooltip spec
2369 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2370 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2374 std::vector<std::string> v_pos = split(parts[0], ',');
2375 std::vector<std::string> v_geom = split(parts[1], ',');
2377 MY_CHECKPOS("tooltip", 0);
2378 MY_CHECKGEOM("tooltip", 1);
2383 if (data->real_coordinates) {
2384 pos = getRealCoordinateBasePos(v_pos);
2385 geom = getRealCoordinateGeometry(v_geom);
2387 pos = getElementBasePos(&v_pos);
2388 geom.X = stof(v_geom[0]) * spacing.X;
2389 geom.Y = stof(v_geom[1]) * spacing.Y;
2392 FieldSpec fieldspec(
2396 258 + m_fields.size()
2399 core::rect<s32> rect(pos, pos + geom);
2401 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2402 data->current_parent, fieldspec.fid, rect);
2404 // the element the rect tooltip is bound to should not block mouse-clicks
2405 e->setVisible(false);
2407 m_fields.push_back(fieldspec);
2408 m_tooltip_rects.emplace_back(e, spec);
2411 m_tooltips[parts[0]] = spec;
2415 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2421 std::vector<std::string> parts = split(data,'[');
2423 if (parts.size() < 2) {
2427 if (trim(parts[0]) != "formspec_version") {
2431 if (is_number(parts[1])) {
2432 m_formspec_version = mystoi(parts[1]);
2439 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2441 if (element.empty())
2444 std::vector<std::string> parts = split(element,'[');
2446 if (parts.size() < 2)
2449 std::string type = trim(parts[0]);
2450 std::string description = trim(parts[1]);
2452 if (type != "size" && type != "invsize")
2455 if (type == "invsize")
2456 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2458 parseSize(data, description);
2463 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2465 if (element.empty())
2468 std::vector<std::string> parts = split(element, '[');
2470 if (parts.size() != 2)
2473 std::string type = trim(parts[0]);
2474 std::string description = trim(parts[1]);
2476 if (type != "position")
2479 parsePosition(data, description);
2484 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2486 std::vector<std::string> parts = split(element, ',');
2488 if (parts.size() == 2) {
2489 data->offset.X = stof(parts[0]);
2490 data->offset.Y = stof(parts[1]);
2494 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2497 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2499 if (element.empty())
2502 std::vector<std::string> parts = split(element, '[');
2504 if (parts.size() != 2)
2507 std::string type = trim(parts[0]);
2508 std::string description = trim(parts[1]);
2510 if (type != "anchor")
2513 parseAnchor(data, description);
2518 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2520 std::vector<std::string> parts = split(element, ',');
2522 if (parts.size() == 2) {
2523 data->anchor.X = stof(parts[0]);
2524 data->anchor.Y = stof(parts[1]);
2528 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2529 << "'" << std::endl;
2532 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2534 std::vector<std::string> parts = split(element, ';');
2536 if (parts.size() < 2) {
2537 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2538 << "'" << std::endl;
2545 for (size_t i = 1; i < parts.size(); i++) {
2546 size_t equal_pos = parts[i].find('=');
2547 if (equal_pos == std::string::npos) {
2548 errorstream << "Invalid style element (Property missing value): '" << element
2549 << "'" << std::endl;
2553 std::string propname = trim(parts[i].substr(0, equal_pos));
2554 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2556 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2558 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2559 if (prop == StyleSpec::NONE) {
2560 if (property_warned.find(propname) != property_warned.end()) {
2561 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2563 << "'" << std::endl;
2564 property_warned.insert(propname);
2569 spec.set(prop, value);
2572 std::vector<std::string> selectors = split(parts[0], ',');
2573 for (size_t sel = 0; sel < selectors.size(); sel++) {
2574 std::string selector = trim(selectors[sel]);
2576 // Copy the style properties to a new StyleSpec
2577 // This allows a separate state mask per-selector
2578 StyleSpec selector_spec = spec;
2580 // Parse state information, if it exists
2581 bool state_valid = true;
2582 size_t state_pos = selector.find(':');
2583 if (state_pos != std::string::npos) {
2584 std::string state_str = selector.substr(state_pos + 1);
2585 selector = selector.substr(0, state_pos);
2587 if (state_str.empty()) {
2588 errorstream << "Invalid style element (Invalid state): '" << element
2589 << "'" << std::endl;
2590 state_valid = false;
2592 std::vector<std::string> states = split(state_str, '+');
2593 for (std::string &state : states) {
2594 StyleSpec::State converted = StyleSpec::getStateByName(state);
2595 if (converted == StyleSpec::STATE_INVALID) {
2596 infostream << "Unknown style state " << state <<
2597 " in element '" << element << "'" << std::endl;
2598 state_valid = false;
2602 selector_spec.addState(converted);
2608 // Skip this selector
2613 theme_by_type[selector].push_back(selector_spec);
2615 theme_by_name[selector].push_back(selector_spec);
2618 // Backwards-compatibility for existing _hovered/_pressed properties
2619 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2620 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2621 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2622 StyleSpec hover_spec;
2623 hover_spec.addState(StyleSpec::STATE_HOVERED);
2625 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2626 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2628 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2629 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2631 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2632 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2636 theme_by_type[selector].push_back(hover_spec);
2638 theme_by_name[selector].push_back(hover_spec);
2641 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2642 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2643 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2644 StyleSpec press_spec;
2645 press_spec.addState(StyleSpec::STATE_PRESSED);
2647 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2648 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2650 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2651 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2653 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2654 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2658 theme_by_type[selector].push_back(press_spec);
2660 theme_by_name[selector].push_back(press_spec);
2668 void GUIFormSpecMenu::parseSetFocus(const std::string &element)
2670 std::vector<std::string> parts = split(element, ';');
2672 if (parts.size() <= 2 ||
2673 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION))
2675 if (m_is_form_regenerated)
2676 return; // Never focus on resizing
2678 bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
2679 if (force_focus || m_text_dst->m_formname != m_last_formname)
2685 errorstream << "Invalid set_focus element (" << parts.size() << "): '" << element
2686 << "'" << std::endl;
2689 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2692 if (element.empty())
2695 if (parseVersionDirect(element))
2698 size_t pos = element.find('[');
2699 if (pos == std::string::npos)
2702 std::string type = trim(element.substr(0, pos));
2703 std::string description = element.substr(pos+1);
2705 if (type == "container") {
2706 parseContainer(data, description);
2710 if (type == "container_end") {
2711 parseContainerEnd(data);
2715 if (type == "list") {
2716 parseList(data, description);
2720 if (type == "listring") {
2721 parseListRing(data, description);
2725 if (type == "checkbox") {
2726 parseCheckbox(data, description);
2730 if (type == "image") {
2731 parseImage(data, description);
2735 if (type == "animated_image") {
2736 parseAnimatedImage(data, description);
2740 if (type == "item_image") {
2741 parseItemImage(data, description);
2745 if (type == "button" || type == "button_exit") {
2746 parseButton(data, description, type);
2750 if (type == "background" || type == "background9") {
2751 parseBackground(data, description);
2755 if (type == "tableoptions"){
2756 parseTableOptions(data,description);
2760 if (type == "tablecolumns"){
2761 parseTableColumns(data,description);
2765 if (type == "table"){
2766 parseTable(data,description);
2770 if (type == "textlist"){
2771 parseTextList(data,description);
2775 if (type == "dropdown"){
2776 parseDropDown(data,description);
2780 if (type == "field_close_on_enter") {
2781 parseFieldCloseOnEnter(data, description);
2785 if (type == "pwdfield") {
2786 parsePwdField(data,description);
2790 if ((type == "field") || (type == "textarea")){
2791 parseField(data,description,type);
2795 if (type == "hypertext") {
2796 parseHyperText(data,description);
2800 if (type == "label") {
2801 parseLabel(data,description);
2805 if (type == "vertlabel") {
2806 parseVertLabel(data,description);
2810 if (type == "item_image_button") {
2811 parseItemImageButton(data,description);
2815 if ((type == "image_button") || (type == "image_button_exit")) {
2816 parseImageButton(data,description,type);
2820 if (type == "tabheader") {
2821 parseTabHeader(data,description);
2825 if (type == "box") {
2826 parseBox(data,description);
2830 if (type == "bgcolor") {
2831 parseBackgroundColor(data,description);
2835 if (type == "listcolors") {
2836 parseListColors(data,description);
2840 if (type == "tooltip") {
2841 parseTooltip(data,description);
2845 if (type == "scrollbar") {
2846 parseScrollBar(data, description);
2850 if (type == "real_coordinates") {
2851 data->real_coordinates = is_yes(description);
2855 if (type == "style") {
2856 parseStyle(data, description, false);
2860 if (type == "style_type") {
2861 parseStyle(data, description, true);
2865 if (type == "scrollbaroptions") {
2866 parseScrollBarOptions(data, description);
2870 if (type == "scroll_container") {
2871 parseScrollContainer(data, description);
2875 if (type == "scroll_container_end") {
2876 parseScrollContainerEnd(data);
2880 if (type == "set_focus") {
2881 parseSetFocus(description);
2886 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2890 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2892 // Useless to regenerate without a screensize
2893 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2899 // Preserve stuff only on same form, not on a new form.
2900 if (m_text_dst->m_formname == m_last_formname) {
2901 // Preserve tables/textlists
2902 for (auto &m_table : m_tables) {
2903 std::string tablename = m_table.first.fname;
2904 GUITable *table = m_table.second;
2905 mydata.table_dyndata[tablename] = table->getDynamicData();
2909 gui::IGUIElement *focused_element = Environment->getFocus();
2910 if (focused_element && focused_element->getParent() == this) {
2911 s32 focused_id = focused_element->getID();
2912 if (focused_id > 257) {
2913 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2914 if (field.fid == focused_id) {
2915 m_focused_element = field.fname;
2922 // Don't keep old focus value
2923 m_focused_element = "";
2929 for (auto &table_it : m_tables)
2930 table_it.second->drop();
2931 for (auto &inventorylist_it : m_inventorylists)
2932 inventorylist_it->drop();
2933 for (auto &checkbox_it : m_checkboxes)
2934 checkbox_it.second->drop();
2935 for (auto &scrollbar_it : m_scrollbars)
2936 scrollbar_it.second->drop();
2937 for (auto &background_it : m_backgrounds)
2938 background_it->drop();
2939 for (auto &tooltip_rect_it : m_tooltip_rects)
2940 tooltip_rect_it.first->drop();
2941 for (auto &clickthrough_it : m_clickthrough_elements)
2942 clickthrough_it->drop();
2943 for (auto &scroll_container_it : m_scroll_containers)
2944 scroll_container_it.second->drop();
2946 mydata.size = v2s32(100, 100);
2947 mydata.screensize = screensize;
2948 mydata.offset = v2f32(0.5f, 0.5f);
2949 mydata.anchor = v2f32(0.5f, 0.5f);
2950 mydata.simple_field_count = 0;
2952 // Base position of contents of form
2953 mydata.basepos = getBasePos();
2955 // the parent for the parsed elements
2956 mydata.current_parent = this;
2958 m_inventorylists.clear();
2959 m_backgrounds.clear();
2961 m_checkboxes.clear();
2962 m_scrollbars.clear();
2965 m_tooltip_rects.clear();
2966 m_inventory_rings.clear();
2967 m_dropdowns.clear();
2968 m_scroll_containers.clear();
2969 theme_by_name.clear();
2970 theme_by_type.clear();
2971 m_clickthrough_elements.clear();
2972 field_close_on_enter.clear();
2973 m_dropdown_index_event.clear();
2975 m_bgnonfullscreen = true;
2976 m_bgfullscreen = false;
2978 m_formspec_version = 1;
2981 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2982 m_bgcolor = video::SColor(
2983 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2984 clamp_u8(myround(formspec_bgcolor.X)),
2985 clamp_u8(myround(formspec_bgcolor.Y)),
2986 clamp_u8(myround(formspec_bgcolor.Z))
2991 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2992 m_fullscreen_bgcolor = video::SColor(
2993 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2994 clamp_u8(myround(formspec_bgcolor.X)),
2995 clamp_u8(myround(formspec_bgcolor.Y)),
2996 clamp_u8(myround(formspec_bgcolor.Z))
3000 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3001 m_default_tooltip_color = video::SColor(255,255,255,255);
3005 assert(!m_tooltip_element);
3006 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3007 m_tooltip_element = gui::StaticText::add(Environment, L"",
3008 core::rect<s32>(0, 0, 110, 18));
3009 m_tooltip_element->enableOverrideColor(true);
3010 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3011 m_tooltip_element->setDrawBackground(true);
3012 m_tooltip_element->setDrawBorder(true);
3013 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3014 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3015 m_tooltip_element->setWordWrap(false);
3016 //we're not parent so no autograb for this one!
3017 m_tooltip_element->grab();
3020 std::vector<std::string> elements = split(m_formspec_string,']');
3023 /* try to read version from first element only */
3024 if (!elements.empty()) {
3025 if (parseVersionDirect(elements[0])) {
3030 /* we need size first in order to calculate image scale */
3031 mydata.explicit_size = false;
3032 for (; i< elements.size(); i++) {
3033 if (!parseSizeDirect(&mydata, elements[i])) {
3038 /* "position" element is always after "size" element if it used */
3039 for (; i< elements.size(); i++) {
3040 if (!parsePositionDirect(&mydata, elements[i])) {
3045 /* "anchor" element is always after "position" (or "size" element) if it used */
3046 for (; i< elements.size(); i++) {
3047 if (!parseAnchorDirect(&mydata, elements[i])) {
3052 /* "no_prepend" element is always after "position" (or "size" element) if it used */
3053 bool enable_prepends = true;
3054 for (; i < elements.size(); i++) {
3055 if (elements[i].empty())
3058 std::vector<std::string> parts = split(elements[i], '[');
3059 if (trim(parts[0]) == "no_prepend")
3060 enable_prepends = false;
3065 /* Copy of the "real_coordinates" element for after the form size. */
3066 mydata.real_coordinates = m_formspec_version >= 2;
3067 for (; i < elements.size(); i++) {
3068 std::vector<std::string> parts = split(elements[i], '[');
3069 std::string name = trim(parts[0]);
3070 if (name != "real_coordinates" || parts.size() != 2)
3071 break; // Invalid format
3073 mydata.real_coordinates = is_yes(trim(parts[1]));
3076 if (mydata.explicit_size) {
3077 // compute scaling for specified form size
3079 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3080 v2u32 delta = current_screensize - m_lockscreensize;
3082 if (current_screensize.Y > m_lockscreensize.Y)
3087 if (current_screensize.X > m_lockscreensize.X)
3092 offset = v2s32(delta.X,delta.Y);
3094 mydata.screensize = m_lockscreensize;
3096 offset = v2s32(0,0);
3099 double gui_scaling = g_settings->getFloat("gui_scaling");
3100 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3104 // In fixed-size mode, inventory image size
3105 // is 0.53 inch multiplied by the gui_scaling
3106 // config parameter. This magic size is chosen
3107 // to make the main menu (15.5 inventory images
3108 // wide, including border) just fit into the
3109 // default window (800 pixels wide) at 96 DPI
3110 // and default scaling (1.00).
3111 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3113 // In variable-size mode, we prefer to make the
3114 // inventory image size 1/15 of screen height,
3115 // multiplied by the gui_scaling config parameter.
3116 // If the preferred size won't fit the whole
3117 // form on the screen, either horizontally or
3118 // vertically, then we scale it down to fit.
3119 // (The magic numbers in the computation of what
3120 // fits arise from the scaling factors in the
3121 // following stanza, including the form border,
3122 // help text space, and 0.1 inventory slot spare.)
3123 // However, a minimum size is also set, that
3124 // the image size can't be less than 0.3 inch
3125 // multiplied by gui_scaling, even if this means
3126 // the form doesn't fit the screen.
3128 // For mobile devices these magic numbers are
3129 // different and forms should always use the
3130 // maximum screen space available.
3131 double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
3132 double fitx_imgsize = mydata.screensize.X /
3133 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
3134 double fity_imgsize = mydata.screensize.Y /
3135 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
3136 use_imgsize = MYMIN(prefer_imgsize,
3137 MYMIN(fitx_imgsize, fity_imgsize));
3139 double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
3140 double fitx_imgsize = mydata.screensize.X /
3141 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3142 double fity_imgsize = mydata.screensize.Y /
3143 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
3144 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3145 double min_imgsize = 0.3 * screen_dpi * gui_scaling;
3146 use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
3147 MYMIN(fitx_imgsize, fity_imgsize)));
3151 // Everything else is scaled in proportion to the
3152 // inventory image size. The inventory slot spacing
3153 // is 5/4 image size horizontally and 15/13 image size
3154 // vertically. The padding around the form (incorporating
3155 // the border of the outer inventory slots) is 3/8
3156 // image size. Font height (baseline to baseline)
3157 // is 2/5 vertical inventory slot spacing, and button
3158 // half-height is 7/8 of font height.
3159 imgsize = v2s32(use_imgsize, use_imgsize);
3160 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3161 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3162 m_btn_height = use_imgsize*15.0/13 * 0.35;
3164 m_font = g_fontengine->getFont();
3166 if (mydata.real_coordinates) {
3167 mydata.size = v2s32(
3168 mydata.invsize.X*imgsize.X,
3169 mydata.invsize.Y*imgsize.Y
3172 mydata.size = v2s32(
3173 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3174 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3178 DesiredRect = mydata.rect = core::rect<s32>(
3179 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3180 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3181 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3182 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3185 // Non-size[] form must consist only of text fields and
3186 // implicit "Proceed" button. Use default font, and
3187 // temporary form size which will be recalculated below.
3188 m_font = g_fontengine->getFont();
3189 m_btn_height = font_line_height(m_font) * 0.875;
3190 DesiredRect = core::rect<s32>(
3191 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3192 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3193 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3194 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3197 recalculateAbsolutePosition(false);
3198 mydata.basepos = getBasePos();
3199 m_tooltip_element->setOverrideFont(m_font);
3201 gui::IGUISkin *skin = Environment->getSkin();
3203 gui::IGUIFont *old_font = skin->getFont();
3204 skin->setFont(m_font);
3206 pos_offset = v2f32();
3208 // used for formspec versions < 3
3209 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3211 if (enable_prepends) {
3212 // Backup the coordinates so that prepends can use the coordinates of choice.
3213 bool rc_backup = mydata.real_coordinates;
3214 u16 version_backup = m_formspec_version;
3215 mydata.real_coordinates = false; // Old coordinates by default.
3217 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3218 for (const auto &element : prepend_elements)
3219 parseElement(&mydata, element);
3221 // legacy sorting for formspec versions < 3
3222 if (m_formspec_version >= 3)
3223 // prepends do not need to be reordered
3224 legacy_sort_start = Children.getLast();
3225 else if (version_backup >= 3)
3226 // only prepends elements have to be reordered
3227 legacySortElements(legacy_sort_start);
3229 m_formspec_version = version_backup;
3230 mydata.real_coordinates = rc_backup; // Restore coordinates
3233 for (; i< elements.size(); i++) {
3234 parseElement(&mydata, elements[i]);
3237 if (mydata.current_parent != this) {
3238 errorstream << "Invalid formspec string: scroll_container was never closed!"
3240 } else if (!container_stack.empty()) {
3241 errorstream << "Invalid formspec string: container was never closed!"
3245 // get the scrollbar elements for scroll_containers
3246 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3247 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3248 if (c.first == b.first.fname) {
3249 c.second->setScrollBar(b.second);
3255 // If there are fields without explicit size[], add a "Proceed"
3256 // button and adjust size to fit all the fields.
3257 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3258 mydata.rect = core::rect<s32>(
3259 mydata.screensize.X / 2 - 580 / 2,
3260 mydata.screensize.Y / 2 - 300 / 2,
3261 mydata.screensize.X / 2 + 580 / 2,
3262 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3265 DesiredRect = mydata.rect;
3266 recalculateAbsolutePosition(false);
3267 mydata.basepos = getBasePos();
3270 v2s32 pos = mydata.basepos;
3271 pos.Y = (mydata.simple_field_count + 2) * 60;
3273 v2s32 size = DesiredRect.getSize();
3274 mydata.rect = core::rect<s32>(
3275 size.X / 2 - 70, pos.Y,
3276 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3278 const wchar_t *text = wgettext("Proceed");
3279 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3284 // Set initial focus if parser didn't set it
3285 gui::IGUIElement *focused_element = Environment->getFocus();
3286 if (!focused_element
3287 || !isMyChild(focused_element)
3288 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3291 skin->setFont(old_font);
3294 if (m_formspec_version < 3)
3295 legacySortElements(legacy_sort_start);
3297 // Formname and regeneration setting
3298 if (!m_is_form_regenerated) {
3299 // Only set previous form name if we purposefully showed a new formspec
3300 m_last_formname = m_text_dst->m_formname;
3301 m_is_form_regenerated = true;
3305 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3308 Draw order for formspec_version <= 2:
3312 0 All other elements
3314 2 item_image, item_image_button
3319 if (from == Children.end())
3320 from = Children.begin();
3324 core::list<IGUIElement *>::Iterator to = Children.end();
3325 // 1: Copy into a sortable container
3326 std::vector<IGUIElement *> elements;
3327 for (auto it = from; it != to; ++it)
3328 elements.emplace_back(*it);
3330 // 2: Sort the container
3331 std::stable_sort(elements.begin(), elements.end(),
3332 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3333 const FieldSpec *spec_a = getSpecByID(a->getID());
3334 const FieldSpec *spec_b = getSpecByID(b->getID());
3335 return spec_a && spec_b &&
3336 spec_a->priority < spec_b->priority;
3339 // 3: Re-assign the pointers
3340 for (auto e : elements) {
3347 bool GUIFormSpecMenu::getAndroidUIInput()
3349 if (!hasAndroidUIInput())
3353 if (porting::getInputDialogState() == -1)
3356 std::string fieldname = m_jni_field_name;
3357 m_jni_field_name.clear();
3359 for (const FieldSpec &field : m_fields) {
3360 if (field.fname != fieldname)
3363 IGUIElement *element = getElementFromId(field.fid, true);
3365 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3368 std::string text = porting::getInputDialogValue();
3369 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3375 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3377 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3379 for (const GUIInventoryList *e : m_inventorylists) {
3380 s32 item_index = e->getItemIndexAtPos(p);
3381 if (item_index != -1)
3382 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3386 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3389 void GUIFormSpecMenu::drawSelectedItem()
3391 video::IVideoDriver* driver = Environment->getVideoDriver();
3393 if (!m_selected_item) {
3394 // reset rotation time
3395 drawItemStack(driver, m_font, ItemStack(),
3396 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3397 m_client, IT_ROT_DRAGGED);
3401 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3403 InventoryList *list = inv->getList(m_selected_item->listname);
3405 ItemStack stack = list->getItem(m_selected_item->i);
3406 stack.count = m_selected_amount;
3408 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3409 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3410 rect.constrainTo(driver->getViewPort());
3411 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3414 void GUIFormSpecMenu::drawMenu()
3417 const std::string &newform = m_form_src->getForm();
3418 if (newform != m_formspec_string) {
3419 m_formspec_string = newform;
3420 m_is_form_regenerated = false;
3421 regenerateGui(m_screensize_old);
3425 gui::IGUISkin* skin = Environment->getSkin();
3426 sanity_check(skin != NULL);
3427 gui::IGUIFont *old_font = skin->getFont();
3428 skin->setFont(m_font);
3430 m_hovered_item_tooltips.clear();
3432 updateSelectedItem();
3434 video::IVideoDriver* driver = Environment->getVideoDriver();
3437 Draw background color
3439 v2u32 screenSize = driver->getScreenSize();
3440 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3443 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3444 if (m_bgnonfullscreen)
3445 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3448 Draw rect_mode tooltip
3450 m_tooltip_element->setVisible(false);
3452 for (const auto &pair : m_tooltip_rects) {
3453 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3454 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3455 const std::wstring &text = pair.second.tooltip;
3456 if (!text.empty()) {
3457 showTooltip(text, pair.second.color, pair.second.bgcolor);
3466 for (gui::IGUIElement *e : m_backgrounds) {
3467 e->setVisible(true);
3469 e->setVisible(false);
3472 // Some elements are only visible while being drawn
3473 for (gui::IGUIElement *e : m_clickthrough_elements)
3474 e->setVisible(true);
3478 (This is where all the drawing happens.)
3480 gui::IGUIElement::draw();
3482 for (gui::IGUIElement *e : m_clickthrough_elements)
3483 e->setVisible(false);
3485 // Draw hovered item tooltips
3486 for (const std::string &tooltip : m_hovered_item_tooltips) {
3487 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3488 m_default_tooltip_bgcolor);
3491 if (m_hovered_item_tooltips.empty()) {
3492 // reset rotation time
3493 drawItemStack(driver, m_font, ItemStack(),
3494 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3495 NULL, m_client, IT_ROT_HOVERED);
3498 /* TODO find way to show tooltips on touchscreen */
3499 #ifndef HAVE_TOUCHSCREENGUI
3500 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3504 Draw fields/buttons tooltips and update the mouse cursor
3506 gui::IGUIElement *hovered =
3507 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3509 #ifndef HAVE_TOUCHSCREENGUI
3510 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3512 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3514 bool hovered_element_found = false;
3516 if (hovered != NULL) {
3518 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3519 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3522 s32 id = hovered->getID();
3525 m_old_tooltip_id = id;
3527 if (id == m_old_tooltip_id) {
3528 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3530 m_hovered_time = porting::getTimeMs();
3531 m_old_tooltip_id = id;
3535 // Find and update the current tooltip and cursor icon
3537 for (const FieldSpec &field : m_fields) {
3539 if (field.fid != id)
3542 if (delta >= m_tooltip_show_delay) {
3543 const std::wstring &text = m_tooltips[field.fname].tooltip;
3545 showTooltip(text, m_tooltips[field.fname].color,
3546 m_tooltips[field.fname].bgcolor);
3549 #ifndef HAVE_TOUCHSCREENGUI
3550 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3551 current_cursor_icon != field.fcursor_icon)
3552 cursor_control->setActiveIcon(field.fcursor_icon);
3555 hovered_element_found = true;
3562 if (!hovered_element_found) {
3563 // no element is hovered
3564 #ifndef HAVE_TOUCHSCREENGUI
3565 if (current_cursor_icon != ECI_NORMAL)
3566 cursor_control->setActiveIcon(ECI_NORMAL);
3570 m_tooltip_element->draw();
3573 Draw dragged item stack
3577 skin->setFont(old_font);
3581 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3582 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3584 EnrichedString ntext(text);
3585 ntext.setDefaultColor(color);
3586 ntext.setBackground(bgcolor);
3588 setStaticText(m_tooltip_element, ntext);
3590 // Tooltip size and offset
3591 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3592 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3594 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3595 int tooltip_offset_x = m_btn_height;
3596 int tooltip_offset_y = m_btn_height;
3598 tooltip_offset_x *= 3;
3599 tooltip_offset_y = 0;
3600 if (m_pointer.X > (s32)screenSize.X / 2)
3601 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3603 // Hide tooltip after ETIE_LEFT_UP
3604 if (m_pointer.X == 0)
3608 // Calculate and set the tooltip position
3609 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3610 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3611 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3612 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3613 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3614 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3616 m_tooltip_element->setRelativePosition(
3618 core::position2d<s32>(tooltip_x, tooltip_y),
3619 core::dimension2d<s32>(tooltip_width, tooltip_height)
3623 // Display the tooltip
3624 m_tooltip_element->setVisible(true);
3625 bringToFront(m_tooltip_element);
3628 void GUIFormSpecMenu::updateSelectedItem()
3630 verifySelectedItem();
3632 // If craftresult is nonempty and nothing else is selected, select it now.
3633 if (!m_selected_item) {
3634 for (const GUIInventoryList *e : m_inventorylists) {
3635 if (e->getListname() != "craftpreview")
3638 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3642 InventoryList *list = inv->getList("craftresult");
3644 if (!list || list->getSize() == 0)
3647 const ItemStack &item = list->getItem(0);
3651 // Grab selected item from the crafting result list
3652 m_selected_item = new GUIInventoryList::ItemSpec;
3653 m_selected_item->inventoryloc = e->getInventoryloc();
3654 m_selected_item->listname = "craftresult";
3655 m_selected_item->i = 0;
3656 m_selected_amount = item.count;
3657 m_selected_dragging = false;
3662 // If craftresult is selected, keep the whole stack selected
3663 if (m_selected_item && m_selected_item->listname == "craftresult")
3664 m_selected_amount = verifySelectedItem().count;
3667 ItemStack GUIFormSpecMenu::verifySelectedItem()
3669 // If the selected stack has become empty for some reason, deselect it.
3670 // If the selected stack has become inaccessible, deselect it.
3671 // If the selected stack has become smaller, adjust m_selected_amount.
3672 // Return the selected stack.
3674 if (m_selected_item) {
3675 if (m_selected_item->isValid()) {
3676 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3678 InventoryList *list = inv->getList(m_selected_item->listname);
3679 if (list && (u32) m_selected_item->i < list->getSize()) {
3680 ItemStack stack = list->getItem(m_selected_item->i);
3681 if (!m_selected_swap.empty()) {
3682 if (m_selected_swap.name == stack.name &&
3683 m_selected_swap.count == stack.count)
3684 m_selected_swap.clear();
3686 m_selected_amount = std::min(m_selected_amount, stack.count);
3695 // selection was not valid
3696 delete m_selected_item;
3697 m_selected_item = nullptr;
3698 m_selected_amount = 0;
3699 m_selected_dragging = false;
3704 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3710 if (quitmode == quit_mode_accept) {
3711 fields["quit"] = "true";
3714 if (quitmode == quit_mode_cancel) {
3715 fields["quit"] = "true";
3716 m_text_dst->gotText(fields);
3720 if (current_keys_pending.key_down) {
3721 fields["key_down"] = "true";
3722 current_keys_pending.key_down = false;
3725 if (current_keys_pending.key_up) {
3726 fields["key_up"] = "true";
3727 current_keys_pending.key_up = false;
3730 if (current_keys_pending.key_enter) {
3731 fields["key_enter"] = "true";
3732 current_keys_pending.key_enter = false;
3735 if (!current_field_enter_pending.empty()) {
3736 fields["key_enter_field"] = current_field_enter_pending;
3737 current_field_enter_pending = "";
3740 if (current_keys_pending.key_escape) {
3741 fields["key_escape"] = "true";
3742 current_keys_pending.key_escape = false;
3745 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3747 std::string name = s.fname;
3748 if (s.ftype == f_Button) {
3749 fields[name] = wide_to_utf8(s.flabel);
3750 } else if (s.ftype == f_Table) {
3751 GUITable *table = getTable(s.fname);
3753 fields[name] = table->checkEvent();
3755 } else if (s.ftype == f_DropDown) {
3756 // No dynamic cast possible due to some distributions shipped
3757 // without rtti support in Irrlicht
3758 IGUIElement *element = getElementFromId(s.fid, true);
3759 gui::IGUIComboBox *e = NULL;
3760 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3761 e = static_cast<gui::IGUIComboBox *>(element);
3763 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3764 << "field without dropdown element" << std::endl;
3767 s32 selected = e->getSelected();
3768 if (selected >= 0) {
3769 if (m_dropdown_index_event.find(s.fname) !=
3770 m_dropdown_index_event.end()) {
3771 fields[name] = std::to_string(selected + 1);
3773 std::vector<std::string> *dropdown_values =
3774 getDropDownValues(s.fname);
3775 if (dropdown_values && selected < (s32)dropdown_values->size())
3776 fields[name] = (*dropdown_values)[selected];
3779 } else if (s.ftype == f_TabHeader) {
3780 // No dynamic cast possible due to some distributions shipped
3781 // without rtti support in Irrlicht
3782 IGUIElement *element = getElementFromId(s.fid, true);
3783 gui::IGUITabControl *e = nullptr;
3784 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3785 e = static_cast<gui::IGUITabControl *>(element);
3789 std::stringstream ss;
3790 ss << (e->getActiveTab() +1);
3791 fields[name] = ss.str();
3793 } else if (s.ftype == f_CheckBox) {
3794 // No dynamic cast possible due to some distributions shipped
3795 // without rtti support in Irrlicht
3796 IGUIElement *element = getElementFromId(s.fid, true);
3797 gui::IGUICheckBox *e = nullptr;
3798 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3799 e = static_cast<gui::IGUICheckBox*>(element);
3804 fields[name] = "true";
3806 fields[name] = "false";
3808 } else if (s.ftype == f_ScrollBar) {
3809 // No dynamic cast possible due to some distributions shipped
3810 // without rtti support in Irrlicht
3811 IGUIElement *element = getElementFromId(s.fid, true);
3812 GUIScrollBar *e = nullptr;
3813 if (element && element->getType() == gui::EGUIET_ELEMENT)
3814 e = static_cast<GUIScrollBar *>(element);
3817 std::stringstream os;
3819 if (s.fdefault == L"Changed")
3820 fields[name] = "CHG:" + os.str();
3822 fields[name] = "VAL:" + os.str();
3824 } else if (s.ftype == f_AnimatedImage) {
3825 // No dynamic cast possible due to some distributions shipped
3826 // without rtti support in Irrlicht
3827 IGUIElement *element = getElementFromId(s.fid, true);
3828 GUIAnimatedImage *e = nullptr;
3829 if (element && element->getType() == gui::EGUIET_ELEMENT)
3830 e = static_cast<GUIAnimatedImage *>(element);
3833 fields[name] = std::to_string(e->getFrameIndex() + 1);
3835 IGUIElement *e = getElementFromId(s.fid, true);
3837 fields[name] = wide_to_utf8(e->getText());
3842 m_text_dst->gotText(fields);
3846 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3848 // The IGUITabControl renders visually using the skin's selected
3849 // font, which we override for the duration of form drawing,
3850 // but computes tab hotspots based on how it would have rendered
3851 // using the font that is selected at the time of button release.
3852 // To make these two consistent, temporarily override the skin's
3853 // font while the IGUITabControl is processing the event.
3854 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3855 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3856 s32 x = event.MouseInput.X;
3857 s32 y = event.MouseInput.Y;
3858 gui::IGUIElement *hovered =
3859 Environment->getRootGUIElement()->getElementFromPoint(
3860 core::position2d<s32>(x, y));
3861 if (hovered && isMyChild(hovered) &&
3862 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3863 gui::IGUISkin* skin = Environment->getSkin();
3864 sanity_check(skin != NULL);
3865 gui::IGUIFont *old_font = skin->getFont();
3866 skin->setFont(m_font);
3867 bool retval = hovered->OnEvent(event);
3868 skin->setFont(old_font);
3873 // Fix Esc/Return key being eaten by checkboxen and tables
3874 if (event.EventType == EET_KEY_INPUT_EVENT) {
3875 KeyPress kp(event.KeyInput);
3876 if (kp == EscapeKey || kp == CancelKey
3877 || kp == getKeySetting("keymap_inventory")
3878 || event.KeyInput.Key==KEY_RETURN) {
3879 gui::IGUIElement *focused = Environment->getFocus();
3880 if (focused && isMyChild(focused) &&
3881 (focused->getType() == gui::EGUIET_LIST_BOX ||
3882 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3883 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3884 event.KeyInput.Key != KEY_RETURN)) {
3890 // Mouse wheel and move events: send to hovered element instead of focused
3891 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3892 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3893 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3894 event.MouseInput.ButtonStates == 0))) {
3895 s32 x = event.MouseInput.X;
3896 s32 y = event.MouseInput.Y;
3897 gui::IGUIElement *hovered =
3898 Environment->getRootGUIElement()->getElementFromPoint(
3899 core::position2d<s32>(x, y));
3900 if (hovered && isMyChild(hovered)) {
3901 hovered->OnEvent(event);
3902 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3906 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3907 /* TODO add a check like:
3908 if (event.JoystickEvent != joystick_we_listen_for)
3911 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3913 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3915 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3917 acceptInput(quit_mode_accept);
3925 return GUIModalMenu::preprocessEvent(event);
3928 void GUIFormSpecMenu::tryClose()
3932 acceptInput(quit_mode_cancel);
3935 m_text_dst->gotText(L"MenuQuit");
3939 enum ButtonEventType : u8
3952 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3954 if (event.EventType==EET_KEY_INPUT_EVENT) {
3955 KeyPress kp(event.KeyInput);
3956 if (event.KeyInput.PressedDown && (
3957 (kp == EscapeKey) || (kp == CancelKey) ||
3958 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3963 if (m_client != NULL && event.KeyInput.PressedDown &&
3964 (kp == getKeySetting("keymap_screenshot"))) {
3965 m_client->makeScreenshot();
3968 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
3969 m_show_debug = !m_show_debug;
3971 if (event.KeyInput.PressedDown &&
3972 (event.KeyInput.Key==KEY_RETURN ||
3973 event.KeyInput.Key==KEY_UP ||
3974 event.KeyInput.Key==KEY_DOWN)
3976 switch (event.KeyInput.Key) {
3978 current_keys_pending.key_enter = true;
3981 current_keys_pending.key_up = true;
3984 current_keys_pending.key_down = true;
3988 //can't happen at all!
3989 FATAL_ERROR("Reached a source line that can't ever been reached");
3992 if (current_keys_pending.key_enter && m_allowclose) {
3993 acceptInput(quit_mode_accept);
4003 /* Mouse event other than movement, or crossing the border of inventory
4004 field while holding right mouse button
4006 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4007 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4008 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4009 event.MouseInput.isRightPressed() &&
4010 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4012 // Get selected item and hovered/clicked item (s)
4014 m_old_tooltip_id = -1;
4015 updateSelectedItem();
4016 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4018 Inventory *inv_selected = NULL;
4019 Inventory *inv_s = NULL;
4020 InventoryList *list_s = NULL;
4022 if (m_selected_item) {
4023 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4024 sanity_check(inv_selected);
4025 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4032 inv_s = m_invmgr->getInventory(s.inventoryloc);
4035 errorstream << "InventoryMenu: The selected inventory location "
4036 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4038 s.i = -1; // make it invalid again
4042 list_s = inv_s->getList(s.listname);
4043 if (list_s == NULL) {
4044 verbosestream << "InventoryMenu: The selected inventory list \""
4045 << s.listname << "\" does not exist" << std::endl;
4046 s.i = -1; // make it invalid again
4050 if ((u32)s.i >= list_s->getSize()) {
4051 infostream << "InventoryMenu: The selected inventory list \""
4052 << s.listname << "\" is too small (i=" << s.i << ", size="
4053 << list_s->getSize() << ")" << std::endl;
4054 s.i = -1; // make it invalid again
4058 s_count = list_s->getItem(s.i).count;
4061 bool identical = m_selected_item && s.isValid() &&
4062 (inv_selected == inv_s) &&
4063 (m_selected_item->listname == s.listname) &&
4064 (m_selected_item->i == s.i);
4066 ButtonEventType button = BET_LEFT;
4067 ButtonEventType updown = BET_OTHER;
4068 switch (event.MouseInput.Event) {
4069 case EMIE_LMOUSE_PRESSED_DOWN:
4070 button = BET_LEFT; updown = BET_DOWN;
4072 case EMIE_RMOUSE_PRESSED_DOWN:
4073 button = BET_RIGHT; updown = BET_DOWN;
4075 case EMIE_MMOUSE_PRESSED_DOWN:
4076 button = BET_MIDDLE; updown = BET_DOWN;
4078 case EMIE_MOUSE_WHEEL:
4079 button = (event.MouseInput.Wheel > 0) ?
4080 BET_WHEEL_UP : BET_WHEEL_DOWN;
4083 case EMIE_LMOUSE_LEFT_UP:
4084 button = BET_LEFT; updown = BET_UP;
4086 case EMIE_RMOUSE_LEFT_UP:
4087 button = BET_RIGHT; updown = BET_UP;
4089 case EMIE_MMOUSE_LEFT_UP:
4090 button = BET_MIDDLE; updown = BET_UP;
4092 case EMIE_MOUSE_MOVED:
4099 // Set this number to a positive value to generate a move action
4100 // from m_selected_item to s.
4101 u32 move_amount = 0;
4103 // Set this number to a positive value to generate a move action
4104 // from s to the next inventory ring.
4105 u32 shift_move_amount = 0;
4107 // Set this number to a positive value to generate a drop action
4108 // from m_selected_item.
4109 u32 drop_amount = 0;
4111 // Set this number to a positive value to generate a craft action at s.
4112 u32 craft_amount = 0;
4116 // Some mouse button has been pressed
4118 //infostream << "Mouse button " << button << " pressed at p=("
4119 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4122 m_selected_dragging = false;
4124 if (s.isValid() && s.listname == "craftpreview") {
4125 // Craft preview has been clicked: craft
4126 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4127 } else if (!m_selected_item) {
4128 if (s_count && button != BET_WHEEL_UP) {
4129 // Non-empty stack has been clicked: select or shift-move it
4130 m_selected_item = new GUIInventoryList::ItemSpec(s);
4133 if (button == BET_RIGHT)
4134 count = (s_count + 1) / 2;
4135 else if (button == BET_MIDDLE)
4136 count = MYMIN(s_count, 10);
4137 else if (button == BET_WHEEL_DOWN)
4142 if (!event.MouseInput.Shift) {
4143 // no shift: select item
4144 m_selected_amount = count;
4145 m_selected_dragging = button != BET_WHEEL_DOWN;
4146 m_auto_place = false;
4148 // shift pressed: move item, right click moves 1
4149 shift_move_amount = button == BET_RIGHT ? 1 : count;
4152 } else { // m_selected_item != NULL
4153 assert(m_selected_amount >= 1);
4156 // Clicked a slot: move
4157 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4159 else if (button == BET_MIDDLE)
4160 move_amount = MYMIN(m_selected_amount, 10);
4161 else if (button == BET_LEFT)
4162 move_amount = m_selected_amount;
4166 if (button == BET_WHEEL_DOWN) {
4167 if (m_selected_amount < s_count)
4168 ++m_selected_amount;
4170 if (move_amount >= m_selected_amount)
4171 m_selected_amount = 0;
4173 m_selected_amount -= move_amount;
4177 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4178 && button != BET_WHEEL_DOWN) {
4179 // Clicked outside of the window: drop
4180 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4182 else if (button == BET_MIDDLE)
4183 drop_amount = MYMIN(m_selected_amount, 10);
4185 drop_amount = m_selected_amount;
4190 // Some mouse button has been released
4192 //infostream<<"Mouse button "<<button<<" released at p=("
4193 // <<p.X<<","<<p.Y<<")"<<std::endl;
4195 if (m_selected_dragging && m_selected_item) {
4198 // Dragged to different slot: move all selected
4199 move_amount = m_selected_amount;
4201 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4202 // Dragged outside of window: drop all selected
4203 drop_amount = m_selected_amount;
4207 m_selected_dragging = false;
4208 // Keep track of whether the mouse button be released
4209 // One click is drag without dropping. Click + release
4210 // + click changes to drop item when moved mode
4211 if (m_selected_item)
4212 m_auto_place = true;
4215 // Mouse has been moved and rmb is down and mouse pointer just
4216 // entered a new inventory field (checked in the entry-if, this
4217 // is the only action here that is generated by mouse movement)
4218 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4220 // TODO: middle mouse to move 10 items might be handy
4222 // Only move an item if the destination slot is empty
4223 // or contains the same item type as what is going to be
4225 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4226 InventoryList *list_to = list_s;
4227 assert(list_from && list_to);
4228 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4229 ItemStack stack_to = list_to->getItem(s.i);
4230 if (stack_to.empty() || stack_to.name == stack_from.name)
4239 // Possibly send inventory action to server
4240 if (move_amount > 0) {
4241 // Send IAction::Move
4243 assert(m_selected_item && m_selected_item->isValid());
4244 assert(s.isValid());
4246 assert(inv_selected && inv_s);
4247 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4248 InventoryList *list_to = list_s;
4249 assert(list_from && list_to);
4250 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4251 ItemStack stack_to = list_to->getItem(s.i);
4253 // Check how many items can be moved
4254 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4255 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4257 // If source stack cannot be added to destination stack at all,
4259 if (leftover.count == stack_from.count &&
4260 leftover.name == stack_from.name) {
4262 if (m_selected_swap.empty()) {
4263 m_selected_amount = stack_to.count;
4264 m_selected_dragging = false;
4266 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4267 // Skip next validation checks due async inventory calls
4268 m_selected_swap = stack_to;
4273 // Source stack goes fully into destination stack
4274 else if (leftover.empty()) {
4275 m_selected_amount -= move_amount;
4277 // Source stack goes partly into destination stack
4279 move_amount -= leftover.count;
4280 m_selected_amount -= move_amount;
4284 infostream << "Handing IAction::Move to manager" << std::endl;
4285 IMoveAction *a = new IMoveAction();
4286 a->count = move_amount;
4287 a->from_inv = m_selected_item->inventoryloc;
4288 a->from_list = m_selected_item->listname;
4289 a->from_i = m_selected_item->i;
4290 a->to_inv = s.inventoryloc;
4291 a->to_list = s.listname;
4293 m_invmgr->inventoryAction(a);
4295 } else if (shift_move_amount > 0) {
4296 u32 mis = m_inventory_rings.size();
4298 for (; i < mis; i++) {
4299 const ListRingSpec &sp = m_inventory_rings[i];
4300 if (sp.inventoryloc == s.inventoryloc
4301 && sp.listname == s.listname)
4305 if (i >= mis) // if not found
4307 u32 to_inv_ind = (i + 1) % mis;
4308 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4309 InventoryList *list_from = list_s;
4312 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4315 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4318 ItemStack stack_from = list_from->getItem(s.i);
4319 assert(shift_move_amount <= stack_from.count);
4321 infostream << "Handing IAction::Move to manager" << std::endl;
4322 IMoveAction *a = new IMoveAction();
4323 a->count = shift_move_amount;
4324 a->from_inv = s.inventoryloc;
4325 a->from_list = s.listname;
4327 a->to_inv = to_inv_sp.inventoryloc;
4328 a->to_list = to_inv_sp.listname;
4329 a->move_somewhere = true;
4330 m_invmgr->inventoryAction(a);
4332 } else if (drop_amount > 0) {
4333 // Send IAction::Drop
4335 assert(m_selected_item && m_selected_item->isValid());
4336 assert(inv_selected);
4337 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4339 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4341 // Check how many items can be dropped
4342 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4343 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4344 m_selected_amount -= drop_amount;
4346 infostream << "Handing IAction::Drop to manager" << std::endl;
4347 IDropAction *a = new IDropAction();
4348 a->count = drop_amount;
4349 a->from_inv = m_selected_item->inventoryloc;
4350 a->from_list = m_selected_item->listname;
4351 a->from_i = m_selected_item->i;
4352 m_invmgr->inventoryAction(a);
4353 } else if (craft_amount > 0) {
4354 assert(s.isValid());
4356 // if there are no items selected or the selected item
4357 // belongs to craftresult list, proceed with crafting
4358 if (!m_selected_item ||
4359 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4363 // Send IACTION_CRAFT
4364 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4365 ICraftAction *a = new ICraftAction();
4366 a->count = craft_amount;
4367 a->craft_inv = s.inventoryloc;
4368 m_invmgr->inventoryAction(a);
4372 // If m_selected_amount has been decreased to zero, deselect
4373 if (m_selected_amount == 0) {
4374 m_selected_swap.clear();
4375 delete m_selected_item;
4376 m_selected_item = nullptr;
4377 m_selected_amount = 0;
4378 m_selected_dragging = false;
4380 m_old_pointer = m_pointer;
4383 if (event.EventType == EET_GUI_EVENT) {
4384 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4386 // find the element that was clicked
4387 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4388 if ((s.ftype == f_TabHeader) &&
4389 (s.fid == event.GUIEvent.Caller->getID())) {
4397 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4399 if (!canTakeFocus(event.GUIEvent.Element)) {
4400 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4402 // Returning true disables focus change
4406 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4407 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4408 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4409 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4410 s32 caller_id = event.GUIEvent.Caller->getID();
4412 if (caller_id == 257) {
4414 acceptInput(quit_mode_accept);
4418 m_text_dst->gotText(L"ExitButton");
4420 // quitMenu deallocates menu
4424 // find the element that was clicked
4425 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4426 // if its a button, set the send field so
4427 // lua knows which button was pressed
4429 if (caller_id != s.fid)
4432 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4436 acceptInput(quit_mode_accept);
4439 m_text_dst->gotText(L"ExitButton");
4444 acceptInput(quit_mode_no);
4448 } else if (s.ftype == f_DropDown) {
4449 // only send the changed dropdown
4450 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4451 if (s2.ftype == f_DropDown) {
4456 acceptInput(quit_mode_no);
4458 // revert configuration to make sure dropdowns are sent on
4459 // regular button click
4460 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4461 if (s2.ftype == f_DropDown) {
4466 } else if (s.ftype == f_ScrollBar) {
4467 s.fdefault = L"Changed";
4468 acceptInput(quit_mode_no);
4470 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4478 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4479 // move scroll_containers
4480 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4481 c.second->onScrollEvent(event.GUIEvent.Caller);
4484 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4485 if (event.GUIEvent.Caller->getID() > 257) {
4486 bool close_on_enter = true;
4487 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4488 if (s.ftype == f_Unknown &&
4489 s.fid == event.GUIEvent.Caller->getID()) {
4490 current_field_enter_pending = s.fname;
4491 std::unordered_map<std::string, bool>::const_iterator it =
4492 field_close_on_enter.find(s.fname);
4493 if (it != field_close_on_enter.end())
4494 close_on_enter = (*it).second;
4500 if (m_allowclose && close_on_enter) {
4501 current_keys_pending.key_enter = true;
4502 acceptInput(quit_mode_accept);
4505 current_keys_pending.key_enter = true;
4508 // quitMenu deallocates menu
4513 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4514 int current_id = event.GUIEvent.Caller->getID();
4515 if (current_id > 257) {
4516 // find the element that was clicked
4517 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4518 // if it's a table, set the send field
4519 // so lua knows which table was changed
4520 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4531 return Parent ? Parent->OnEvent(event) : false;
4535 * get name of element by element id
4536 * @param id of element
4537 * @return name string or empty string
4539 std::string GUIFormSpecMenu::getNameByID(s32 id)
4541 for (FieldSpec &spec : m_fields) {
4549 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4551 for (FieldSpec &spec : m_fields) {
4559 * get label of element by id
4560 * @param id of element
4561 * @return label string or empty string
4563 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4565 for (FieldSpec &spec : m_fields) {
4572 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4573 const std::string &name, const std::string &parent_type) {
4574 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4577 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4578 const std::string &type, const std::string &name, const std::string &parent_type)
4580 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4582 auto it = theme_by_type.find("*");
4583 if (it != theme_by_type.end()) {
4584 for (const StyleSpec &spec : it->second)
4585 ret[(u32)spec.getState()] |= spec;
4588 it = theme_by_name.find("*");
4589 if (it != theme_by_name.end()) {
4590 for (const StyleSpec &spec : it->second)
4591 ret[(u32)spec.getState()] |= spec;
4594 if (!parent_type.empty()) {
4595 it = theme_by_type.find(parent_type);
4596 if (it != theme_by_type.end()) {
4597 for (const StyleSpec &spec : it->second)
4598 ret[(u32)spec.getState()] |= spec;
4602 it = theme_by_type.find(type);
4603 if (it != theme_by_type.end()) {
4604 for (const StyleSpec &spec : it->second)
4605 ret[(u32)spec.getState()] |= spec;
4608 it = theme_by_name.find(name);
4609 if (it != theme_by_name.end()) {
4610 for (const StyleSpec &spec : it->second)
4611 ret[(u32)spec.getState()] |= spec;