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.
27 #include "guiFormSpecMenu.h"
28 #include "constants.h"
30 #include "client/keycode.h"
31 #include "util/strfnd.h"
32 #include <IGUIButton.h>
33 #include <IGUICheckBox.h>
34 #include <IGUIComboBox.h>
35 #include <IGUIEditBox.h>
36 #include <IGUIStaticText.h>
38 #include <IGUITabControl.h>
39 #include "client/renderingengine.h"
41 #include "client/tile.h" // ITextureSource
42 #include "client/hud.h" // drawItemStack
46 #include "scripting_server.h"
47 #include "mainmenumanager.h"
50 #include "client/client.h"
51 #include "client/fontengine.h"
52 #include "client/sound.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "guiAnimatedImage.h"
59 #include "guiBackgroundImage.h"
61 #include "guiButton.h"
62 #include "guiButtonImage.h"
63 #include "guiButtonItemImage.h"
64 #include "guiEditBoxWithScrollbar.h"
65 #include "guiInventoryList.h"
66 #include "guiItemImage.h"
67 #include "guiScrollContainer.h"
68 #include "guiHyperText.h"
71 #define MY_CHECKPOS(a,b) \
72 if (v_pos.size() != 2) { \
73 errorstream<< "Invalid pos for element " << a << " specified: \"" \
74 << parts[b] << "\"" << std::endl; \
78 #define MY_CHECKGEOM(a,b) \
79 if (v_geom.size() != 2) { \
80 errorstream<< "Invalid geometry for element " << a << \
81 " specified: \"" << parts[b] << "\"" << std::endl; \
85 #define MY_CHECKCLIENT(a) \
87 errorstream << "Attempted to use element " << a << " with m_client == nullptr." << std::endl; \
94 static unsigned int font_line_height(gui::IGUIFont *font)
96 return font->getDimension(L"Ay").Height + font->getKerningHeight();
99 inline u32 clamp_u8(s32 value)
101 return (u32) MYMIN(MYMAX(value, 0), 255);
104 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
105 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
106 Client *client, gui::IGUIEnvironment *guienv, ISimpleTextureSource *tsrc,
107 ISoundManager *sound_manager, IFormSource *fsrc, TextDest *tdst,
108 const std::string &formspecPrepend, bool remap_dbl_click):
109 GUIModalMenu(guienv, parent, id, menumgr, remap_dbl_click),
112 m_sound_manager(sound_manager),
114 m_formspec_prepend(formspecPrepend),
119 current_keys_pending.key_down = false;
120 current_keys_pending.key_up = false;
121 current_keys_pending.key_enter = false;
122 current_keys_pending.key_escape = false;
124 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
125 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
128 GUIFormSpecMenu::~GUIFormSpecMenu()
133 for (auto &table_it : m_tables)
134 table_it.second->drop();
135 for (auto &inventorylist_it : m_inventorylists)
136 inventorylist_it->drop();
137 for (auto &checkbox_it : m_checkboxes)
138 checkbox_it.second->drop();
139 for (auto &scrollbar_it : m_scrollbars)
140 scrollbar_it.second->drop();
141 for (auto &tooltip_rect_it : m_tooltip_rects)
142 tooltip_rect_it.first->drop();
143 for (auto &clickthrough_it : m_clickthrough_elements)
144 clickthrough_it->drop();
145 for (auto &scroll_container_it : m_scroll_containers)
146 scroll_container_it.second->drop();
148 delete m_selected_item;
153 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
154 gui::IGUIEnvironment *guienv, JoystickController *joystick, IFormSource *fs_src,
155 TextDest *txt_dest, const std::string &formspecPrepend, ISoundManager *sound_manager)
157 if (cur_formspec == nullptr) {
158 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
159 client, guienv, client->getTextureSource(), sound_manager, fs_src,
160 txt_dest, formspecPrepend);
161 cur_formspec->doPause = false;
164 Caution: do not call (*cur_formspec)->drop() here --
165 the reference might outlive the menu, so we will
166 periodically check if *cur_formspec is the only
167 remaining reference (i.e. the menu was removed)
168 and delete it in that case.
172 cur_formspec->setFormspecPrepend(formspecPrepend);
173 cur_formspec->setFormSource(fs_src);
174 cur_formspec->setTextDest(txt_dest);
178 void GUIFormSpecMenu::removeTooltip()
180 if (m_tooltip_element) {
181 m_tooltip_element->remove();
182 m_tooltip_element->drop();
183 m_tooltip_element = nullptr;
187 void GUIFormSpecMenu::setInitialFocus()
189 // Set initial focus according to following order of precedence:
190 // 1. first empty editbox
194 // 5. first focusable (not statictext, not tabheader)
195 // 6. first child element
197 const auto& children = getChildren();
199 // 1. first empty editbox
200 for (gui::IGUIElement *it : children) {
201 if (it->getType() == gui::EGUIET_EDIT_BOX
202 && it->getText()[0] == 0) {
203 Environment->setFocus(it);
209 for (gui::IGUIElement *it : children) {
210 if (it->getType() == gui::EGUIET_EDIT_BOX) {
211 Environment->setFocus(it);
217 for (gui::IGUIElement *it : children) {
218 if (it->getTypeName() == std::string("GUITable")) {
219 Environment->setFocus(it);
225 for (auto it = children.rbegin(); it != children.rend(); ++it) {
226 if ((*it)->getType() == gui::EGUIET_BUTTON) {
227 Environment->setFocus(*it);
232 // 5. first focusable (not statictext, not tabheader)
233 for (gui::IGUIElement *it : children) {
234 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
235 it->getType() != gui::EGUIET_TAB_CONTROL) {
236 Environment->setFocus(it);
241 // 6. first child element
242 if (children.empty())
243 Environment->setFocus(this);
245 Environment->setFocus(children.front());
248 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
250 for (auto &table : m_tables) {
251 if (tablename == table.first.fname)
257 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
259 for (auto &dropdown : m_dropdowns) {
260 if (name == dropdown.first.fname)
261 return &dropdown.second;
266 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
268 v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
270 pos_f.X += stof((*v_pos)[0]) * spacing.X;
271 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
273 return v2s32(pos_f.X, pos_f.Y);
276 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
278 return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
279 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
282 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
284 return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
287 bool GUIFormSpecMenu::precheckElement(const std::string &name, const std::string &element,
288 size_t args_min, size_t args_max, std::vector<std::string> &parts)
290 parts = split(element, ';');
291 if (parts.size() >= args_min && (parts.size() <= args_max || m_formspec_version > FORMSPEC_API_VERSION))
294 errorstream << "Invalid " << name << " element(" << parts.size() << "): '" << element << "'" << std::endl;
298 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
300 // Note: do not use precheckElement due to "," separator.
301 std::vector<std::string> parts = split(element,',');
303 if (((parts.size() == 2) || parts.size() == 3) ||
304 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
306 if (parts[1].find(';') != std::string::npos)
307 parts[1] = parts[1].substr(0,parts[1].find(';'));
309 data->invsize.X = MYMAX(0, stof(parts[0]));
310 data->invsize.Y = MYMAX(0, stof(parts[1]));
313 #ifndef HAVE_TOUCHSCREENGUI
314 if (parts.size() == 3) {
315 if (parts[2] == "true") {
316 lockSize(true,v2u32(800,600));
320 data->explicit_size = true;
323 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
326 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
328 std::vector<std::string> parts = split(element, ',');
330 if (parts.size() >= 2) {
331 if (parts[1].find(';') != std::string::npos)
332 parts[1] = parts[1].substr(0, parts[1].find(';'));
334 container_stack.push(pos_offset);
335 pos_offset.X += stof(parts[0]);
336 pos_offset.Y += stof(parts[1]);
339 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
342 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
344 if (container_stack.empty()) {
345 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
347 pos_offset = container_stack.top();
348 container_stack.pop();
352 void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
354 std::vector<std::string> parts;
355 if (!precheckElement("scroll_container start", element, 4, 5, parts))
358 std::vector<std::string> v_pos = split(parts[0], ',');
359 std::vector<std::string> v_geom = split(parts[1], ',');
360 std::string scrollbar_name = parts[2];
361 std::string orientation = parts[3];
362 f32 scroll_factor = 0.1f;
363 if (parts.size() >= 5 && !parts[4].empty())
364 scroll_factor = stof(parts[4]);
366 MY_CHECKPOS("scroll_container", 0);
367 MY_CHECKGEOM("scroll_container", 1);
369 v2s32 pos = getRealCoordinateBasePos(v_pos);
370 v2s32 geom = getRealCoordinateGeometry(v_geom);
372 if (orientation == "vertical")
373 scroll_factor *= -imgsize.Y;
374 else if (orientation == "horizontal")
375 scroll_factor *= -imgsize.X;
377 warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
378 << "Invalid scroll_container orientation: " << orientation
381 // old parent (at first: this)
382 // ^ is parent of clipper
383 // ^ is parent of mover
384 // ^ is parent of other elements
387 core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
389 gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
390 data->current_parent, 0, rect_clipper);
393 FieldSpec spec_mover(
397 258 + m_fields.size()
400 core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
402 GUIScrollContainer *mover = new GUIScrollContainer(Environment,
403 clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
405 data->current_parent = mover;
407 m_scroll_containers.emplace_back(scrollbar_name, mover);
409 m_fields.push_back(spec_mover);
413 // remove interferring offset of normal containers
414 container_stack.push(pos_offset);
419 void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
421 if (data->current_parent == this || data->current_parent->getParent() == this ||
422 container_stack.empty()) {
423 errorstream << "Invalid scroll_container end element, "
424 << "no matching scroll_container start element" << std::endl;
428 if (pos_offset.getLengthSQ() != 0.0f) {
429 // pos_offset is only set by containers and scroll_containers.
430 // scroll_containers always set it to 0,0 which means that if it is
431 // not 0,0, it is a normal container that was opened last, not a
433 errorstream << "Invalid scroll_container end element, "
434 << "an inner container was left open" << std::endl;
438 data->current_parent = data->current_parent->getParent()->getParent();
439 pos_offset = container_stack.top();
440 container_stack.pop();
443 void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
445 MY_CHECKCLIENT("list");
447 std::vector<std::string> parts;
448 if (!precheckElement("list", element, 4, 5, parts))
451 std::string location = parts[0];
452 std::string listname = parts[1];
453 std::vector<std::string> v_pos = split(parts[2],',');
454 std::vector<std::string> v_geom = split(parts[3],',');
455 std::string startindex;
456 if (parts.size() == 5)
457 startindex = parts[4];
459 MY_CHECKPOS("list",2);
460 MY_CHECKGEOM("list",3);
462 InventoryLocation loc;
464 if (location == "context" || location == "current_name")
465 loc = m_current_inventory_location;
467 loc.deSerialize(location);
470 geom.X = stoi(v_geom[0]);
471 geom.Y = stoi(v_geom[1]);
474 if (!startindex.empty())
475 start_i = stoi(startindex);
477 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
478 errorstream << "Invalid list element: '" << element << "'" << std::endl;
482 if (!data->explicit_size)
483 warningstream << "invalid use of list without a size[] element" << std::endl;
489 258 + m_fields.size(),
493 auto style = getDefaultStyleForElement("list", spec.fname);
495 v2f32 slot_scale = style.getVector2f(StyleSpec::SIZE, v2f32(0, 0));
497 slot_scale.X <= 0 ? imgsize.X : std::max<f32>(slot_scale.X * imgsize.X, 1),
498 slot_scale.Y <= 0 ? imgsize.Y : std::max<f32>(slot_scale.Y * imgsize.Y, 1)
501 v2f32 slot_spacing = style.getVector2f(StyleSpec::SPACING, v2f32(-1, -1));
502 v2f32 default_spacing = data->real_coordinates ?
503 v2f32(imgsize.X * 0.25f, imgsize.Y * 0.25f) :
504 v2f32(spacing.X - imgsize.X, spacing.Y - imgsize.Y);
506 slot_spacing.X = slot_spacing.X < 0 ? default_spacing.X :
507 imgsize.X * slot_spacing.X;
508 slot_spacing.Y = slot_spacing.Y < 0 ? default_spacing.Y :
509 imgsize.Y * slot_spacing.Y;
511 slot_spacing += slot_size;
513 v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) :
514 getElementBasePos(&v_pos);
516 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
517 pos.X + (geom.X - 1) * slot_spacing.X + slot_size.X,
518 pos.Y + (geom.Y - 1) * slot_spacing.Y + slot_size.Y);
520 GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
521 spec.fid, rect, m_invmgr, loc, listname, geom, start_i,
522 v2s32(slot_size.X, slot_size.Y), slot_spacing, this,
523 data->inventorylist_options, m_font);
525 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
527 m_inventorylists.push_back(e);
528 m_fields.push_back(spec);
531 void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
533 MY_CHECKCLIENT("listring");
535 std::vector<std::string> parts = split(element, ';');
537 if (parts.size() == 2) {
538 std::string location = parts[0];
539 std::string listname = parts[1];
541 InventoryLocation loc;
543 if (location == "context" || location == "current_name")
544 loc = m_current_inventory_location;
546 loc.deSerialize(location);
548 m_inventory_rings.emplace_back(loc, listname);
552 if (element.empty() && m_inventorylists.size() > 1) {
553 size_t siz = m_inventorylists.size();
554 // insert the last two inv list elements into the list ring
555 const GUIInventoryList *spa = m_inventorylists[siz - 2];
556 const GUIInventoryList *spb = m_inventorylists[siz - 1];
557 m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname());
558 m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname());
562 errorstream<< "Invalid list ring element(" << parts.size() << ", "
563 << m_inventorylists.size() << "): '" << element << "'" << std::endl;
566 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
568 std::vector<std::string> parts;
569 if (!precheckElement("checkbox", element, 3, 4, parts))
572 std::vector<std::string> v_pos = split(parts[0],',');
573 std::string name = parts[1];
574 std::string label = parts[2];
575 std::string selected;
577 if (parts.size() >= 4)
580 MY_CHECKPOS("checkbox",0);
582 bool fselected = false;
584 if (selected == "true")
587 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
588 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
589 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
590 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
593 core::rect<s32> rect;
595 if (data->real_coordinates) {
596 pos = getRealCoordinateBasePos(v_pos);
598 rect = core::rect<s32>(
601 pos.X + label_size.Width + cb_size + 7,
605 pos = getElementBasePos(&v_pos);
606 rect = core::rect<s32>(
608 pos.Y + imgsize.Y / 2 - y_center,
609 pos.X + label_size.Width + cb_size + 7,
610 pos.Y + imgsize.Y / 2 + y_center
616 wlabel, //Needed for displaying text on MSVC
621 spec.ftype = f_CheckBox;
623 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
624 data->current_parent, spec.fid, spec.flabel.c_str());
626 auto style = getDefaultStyleForElement("checkbox", name);
628 spec.sound = style.get(StyleSpec::Property::SOUND, "");
630 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
632 if (spec.fname == m_focused_element) {
633 Environment->setFocus(e);
637 m_checkboxes.emplace_back(spec, e);
638 m_fields.push_back(spec);
641 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
643 std::vector<std::string> parts;
644 if (!precheckElement("scrollbar", element, 5, 5, parts))
647 std::vector<std::string> v_pos = split(parts[0],',');
648 std::vector<std::string> v_geom = split(parts[1],',');
649 std::string name = parts[3];
650 std::string value = parts[4];
652 MY_CHECKPOS("scrollbar",0);
653 MY_CHECKGEOM("scrollbar",1);
658 if (data->real_coordinates) {
659 pos = getRealCoordinateBasePos(v_pos);
660 dim = getRealCoordinateGeometry(v_geom);
662 pos = getElementBasePos(&v_pos);
663 dim.X = stof(v_geom[0]) * spacing.X;
664 dim.Y = stof(v_geom[1]) * spacing.Y;
667 core::rect<s32> rect =
668 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
677 bool is_horizontal = true;
679 if (parts[2] == "vertical")
680 is_horizontal = false;
682 spec.ftype = f_ScrollBar;
684 GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent,
685 spec.fid, rect, is_horizontal, true);
687 auto style = getDefaultStyleForElement("scrollbar", name);
688 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
689 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
691 s32 max = data->scrollbar_options.max;
692 s32 min = data->scrollbar_options.min;
697 e->setPos(stoi(parts[4]));
699 e->setSmallStep(data->scrollbar_options.small_step);
700 e->setLargeStep(data->scrollbar_options.large_step);
702 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
704 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
706 if (spec.fname == m_focused_element) {
707 Environment->setFocus(e);
710 m_scrollbars.emplace_back(spec,e);
711 m_fields.push_back(spec);
714 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
716 std::vector<std::string> parts = split(element, ';');
718 if (parts.size() == 0) {
719 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
720 element << "'" << std::endl;
724 for (const std::string &i : parts) {
725 std::vector<std::string> options = split(i, '=');
727 if (options.size() != 2) {
728 warningstream << "Invalid scrollbaroptions option syntax: '" <<
729 element << "'" << std::endl;
730 continue; // Go to next option
733 if (options[0] == "max") {
734 data->scrollbar_options.max = stoi(options[1]);
736 } else if (options[0] == "min") {
737 data->scrollbar_options.min = stoi(options[1]);
739 } else if (options[0] == "smallstep") {
740 int value = stoi(options[1]);
741 data->scrollbar_options.small_step = value < 0 ? 10 : value;
743 } else if (options[0] == "largestep") {
744 int value = stoi(options[1]);
745 data->scrollbar_options.large_step = value < 0 ? 100 : value;
747 } else if (options[0] == "thumbsize") {
748 int value = stoi(options[1]);
749 data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
751 } else if (options[0] == "arrows") {
752 std::string value = trim(options[1]);
754 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
755 else if (value == "show")
756 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
757 else // Auto hide/show
758 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
762 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
763 "): '" << element << "'" << std::endl;
767 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
769 std::vector<std::string> parts;
770 if (!precheckElement("image", element, 2, 3, parts))
773 if (parts.size() >= 3) {
774 std::vector<std::string> v_pos = split(parts[0],',');
775 std::vector<std::string> v_geom = split(parts[1],',');
776 std::string name = unescape_string(parts[2]);
778 MY_CHECKPOS("image", 0);
779 MY_CHECKGEOM("image", 1);
784 if (data->real_coordinates) {
785 pos = getRealCoordinateBasePos(v_pos);
786 geom = getRealCoordinateGeometry(v_geom);
788 pos = getElementBasePos(&v_pos);
789 geom.X = stof(v_geom[0]) * (float)imgsize.X;
790 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
793 if (!data->explicit_size)
794 warningstream<<"invalid use of image without a size[] element"<<std::endl;
796 video::ITexture *texture = m_tsrc->getTexture(name);
798 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
799 << std::endl << "\t" << name << std::endl;
807 258 + m_fields.size(),
810 core::rect<s32> rect(pos, pos + geom);
811 gui::IGUIImage *e = Environment->addImage(rect, data->current_parent,
813 e->setImage(texture);
814 e->setScaleImage(true);
815 auto style = getDefaultStyleForElement("image", spec.fname);
816 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
817 m_fields.push_back(spec);
819 // images should let events through
821 m_clickthrough_elements.push_back(e);
825 // Else: 2 arguments in "parts"
827 std::vector<std::string> v_pos = split(parts[0],',');
828 std::string name = unescape_string(parts[1]);
830 MY_CHECKPOS("image", 0);
832 v2s32 pos = getElementBasePos(&v_pos);
834 if (!data->explicit_size)
835 warningstream<<"invalid use of image without a size[] element"<<std::endl;
837 video::ITexture *texture = m_tsrc->getTexture(name);
839 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
840 << std::endl << "\t" << name << std::endl;
848 258 + m_fields.size()
850 gui::IGUIImage *e = Environment->addImage(texture, pos, true,
851 data->current_parent, spec.fid, 0);
852 auto style = getDefaultStyleForElement("image", spec.fname);
853 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
854 m_fields.push_back(spec);
856 // images should let events through
858 m_clickthrough_elements.push_back(e);
861 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
863 std::vector<std::string> parts;
864 if (!precheckElement("animated_image", element, 6, 7, parts))
867 std::vector<std::string> v_pos = split(parts[0], ',');
868 std::vector<std::string> v_geom = split(parts[1], ',');
869 std::string name = parts[2];
870 std::string texture_name = unescape_string(parts[3]);
871 s32 frame_count = stoi(parts[4]);
872 s32 frame_duration = stoi(parts[5]);
874 MY_CHECKPOS("animated_image", 0);
875 MY_CHECKGEOM("animated_image", 1);
880 if (data->real_coordinates) {
881 pos = getRealCoordinateBasePos(v_pos);
882 geom = getRealCoordinateGeometry(v_geom);
884 pos = getElementBasePos(&v_pos);
885 geom.X = stof(v_geom[0]) * (float)imgsize.X;
886 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
889 if (!data->explicit_size)
890 warningstream << "Invalid use of animated_image without a size[] element" << std::endl;
896 258 + m_fields.size()
898 spec.ftype = f_AnimatedImage;
901 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
903 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent, spec.fid,
904 rect, texture_name, frame_count, frame_duration, m_tsrc);
906 if (parts.size() >= 7)
907 e->setFrameIndex(stoi(parts[6]) - 1);
909 auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
910 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
912 // Animated images should let events through
913 m_clickthrough_elements.push_back(e);
915 m_fields.push_back(spec);
918 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
920 std::vector<std::string> parts;
921 if (!precheckElement("item_image", element, 3, 3, parts))
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("item_image",0);
929 MY_CHECKGEOM("item_image",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 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
967 const std::string &type)
969 std::vector<std::string> parts;
970 if (!precheckElement("button", element, 4, 4, parts))
973 std::vector<std::string> v_pos = split(parts[0],',');
974 std::vector<std::string> v_geom = split(parts[1],',');
975 std::string name = parts[2];
976 std::string label = parts[3];
978 MY_CHECKPOS("button",0);
979 MY_CHECKGEOM("button",1);
983 core::rect<s32> rect;
985 if (data->real_coordinates) {
986 pos = getRealCoordinateBasePos(v_pos);
987 geom = getRealCoordinateGeometry(v_geom);
988 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
991 pos = getElementBasePos(&v_pos);
992 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
993 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
995 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
996 pos.X + geom.X, pos.Y + m_btn_height);
999 if(!data->explicit_size)
1000 warningstream<<"invalid use of button without a size[] element"<<std::endl;
1002 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1008 258 + m_fields.size()
1010 spec.ftype = f_Button;
1011 if(type == "button_exit")
1012 spec.is_exit = true;
1014 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1015 data->current_parent, spec.fid, spec.flabel.c_str());
1017 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1019 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1021 e->setStyles(style);
1023 if (spec.fname == m_focused_element) {
1024 Environment->setFocus(e);
1027 m_fields.push_back(spec);
1030 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1032 std::vector<std::string> parts;
1033 if (!precheckElement("background", element, 3, 5, parts))
1036 std::vector<std::string> v_pos = split(parts[0],',');
1037 std::vector<std::string> v_geom = split(parts[1],',');
1038 std::string name = unescape_string(parts[2]);
1040 MY_CHECKPOS("background",0);
1041 MY_CHECKGEOM("background",1);
1046 if (data->real_coordinates) {
1047 pos = getRealCoordinateBasePos(v_pos);
1048 geom = getRealCoordinateGeometry(v_geom);
1050 pos = getElementBasePos(&v_pos);
1051 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1052 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1054 geom.X = stof(v_geom[0]) * spacing.X;
1055 geom.Y = stof(v_geom[1]) * spacing.Y;
1059 if (parts.size() >= 4 && is_yes(parts[3])) {
1060 if (data->real_coordinates) {
1061 pos = getRealCoordinateBasePos(v_pos) * -1;
1064 pos.X = stoi(v_pos[0]); //acts as offset
1065 pos.Y = stoi(v_pos[1]);
1070 core::rect<s32> middle;
1071 if (parts.size() >= 5) {
1072 std::vector<std::string> v_middle = split(parts[4], ',');
1073 if (v_middle.size() == 1) {
1074 s32 x = stoi(v_middle[0]);
1075 middle.UpperLeftCorner = core::vector2di(x, x);
1076 middle.LowerRightCorner = core::vector2di(-x, -x);
1077 } else if (v_middle.size() == 2) {
1078 s32 x = stoi(v_middle[0]);
1079 s32 y = stoi(v_middle[1]);
1080 middle.UpperLeftCorner = core::vector2di(x, y);
1081 middle.LowerRightCorner = core::vector2di(-x, -y);
1082 // `-x` is interpreted as `w - x`
1083 } else if (v_middle.size() == 4) {
1084 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1085 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1087 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1091 if (!data->explicit_size && !clip)
1092 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1098 258 + m_fields.size()
1101 core::rect<s32> rect;
1103 // no auto_clip => position like normal image
1104 rect = core::rect<s32>(pos, pos + geom);
1106 // it will be auto-clipped when drawing
1107 rect = core::rect<s32>(-pos, pos);
1110 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, data->background_parent.get(),
1111 spec.fid, rect, name, middle, m_tsrc, clip);
1113 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1115 e->setNotClipped(true);
1117 m_fields.push_back(spec);
1121 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1123 std::vector<std::string> parts = split(element,';');
1125 data->table_options.clear();
1126 for (const std::string &part : parts) {
1127 // Parse table option
1128 std::string opt = unescape_string(part);
1129 data->table_options.push_back(GUITable::splitOption(opt));
1133 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1135 std::vector<std::string> parts = split(element,';');
1137 data->table_columns.clear();
1138 for (const std::string &part : parts) {
1139 std::vector<std::string> col_parts = split(part,',');
1140 GUITable::TableColumn column;
1141 // Parse column type
1142 if (!col_parts.empty())
1143 column.type = col_parts[0];
1144 // Parse column options
1145 for (size_t j = 1; j < col_parts.size(); ++j) {
1146 std::string opt = unescape_string(col_parts[j]);
1147 column.options.push_back(GUITable::splitOption(opt));
1149 data->table_columns.push_back(column);
1153 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1155 std::vector<std::string> parts;
1156 if (!precheckElement("table", element, 4, 5, parts))
1159 std::vector<std::string> v_pos = split(parts[0],',');
1160 std::vector<std::string> v_geom = split(parts[1],',');
1161 std::string name = parts[2];
1162 std::vector<std::string> items = split(parts[3],',');
1163 std::string str_initial_selection;
1164 std::string str_transparent = "false";
1166 if (parts.size() >= 5)
1167 str_initial_selection = parts[4];
1169 MY_CHECKPOS("table",0);
1170 MY_CHECKGEOM("table",1);
1175 if (data->real_coordinates) {
1176 pos = getRealCoordinateBasePos(v_pos);
1177 geom = getRealCoordinateGeometry(v_geom);
1179 pos = getElementBasePos(&v_pos);
1180 geom.X = stof(v_geom[0]) * spacing.X;
1181 geom.Y = stof(v_geom[1]) * spacing.Y;
1184 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1190 258 + m_fields.size()
1193 spec.ftype = f_Table;
1195 for (std::string &item : items) {
1196 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1199 //now really show table
1200 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1203 if (spec.fname == m_focused_element) {
1204 Environment->setFocus(e);
1207 e->setTable(data->table_options, data->table_columns, items);
1209 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1210 e->setDynamicData(data->table_dyndata[name]);
1213 if (!str_initial_selection.empty() && str_initial_selection != "0")
1214 e->setSelected(stoi(str_initial_selection));
1216 auto style = getDefaultStyleForElement("table", name);
1217 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1218 e->setOverrideFont(style.getFont());
1220 m_tables.emplace_back(spec, e);
1221 m_fields.push_back(spec);
1224 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1226 std::vector<std::string> parts;
1227 if (!precheckElement("textlist", element, 4, 6, parts))
1230 std::vector<std::string> v_pos = split(parts[0],',');
1231 std::vector<std::string> v_geom = split(parts[1],',');
1232 std::string name = parts[2];
1233 std::vector<std::string> items = split(parts[3],',');
1234 std::string str_initial_selection;
1235 std::string str_transparent = "false";
1237 if (parts.size() >= 5)
1238 str_initial_selection = parts[4];
1240 if (parts.size() >= 6)
1241 str_transparent = parts[5];
1243 MY_CHECKPOS("textlist",0);
1244 MY_CHECKGEOM("textlist",1);
1249 if (data->real_coordinates) {
1250 pos = getRealCoordinateBasePos(v_pos);
1251 geom = getRealCoordinateGeometry(v_geom);
1253 pos = getElementBasePos(&v_pos);
1254 geom.X = stof(v_geom[0]) * spacing.X;
1255 geom.Y = stof(v_geom[1]) * spacing.Y;
1258 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1264 258 + m_fields.size()
1267 spec.ftype = f_Table;
1269 for (std::string &item : items) {
1270 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1273 //now really show list
1274 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1277 if (spec.fname == m_focused_element) {
1278 Environment->setFocus(e);
1281 e->setTextList(items, is_yes(str_transparent));
1283 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1284 e->setDynamicData(data->table_dyndata[name]);
1287 if (!str_initial_selection.empty() && str_initial_selection != "0")
1288 e->setSelected(stoi(str_initial_selection));
1290 auto style = getDefaultStyleForElement("textlist", name);
1291 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1292 e->setOverrideFont(style.getFont());
1294 m_tables.emplace_back(spec, e);
1295 m_fields.push_back(spec);
1298 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1300 std::vector<std::string> parts;
1301 if (!precheckElement("dropdown", element, 5, 6, parts))
1304 std::vector<std::string> v_pos = split(parts[0], ',');
1305 std::string name = parts[2];
1306 std::vector<std::string> items = split(parts[3], ',');
1307 std::string str_initial_selection = parts[4];
1309 if (parts.size() >= 6 && is_yes(parts[5]))
1310 m_dropdown_index_event[name] = true;
1312 MY_CHECKPOS("dropdown",0);
1316 core::rect<s32> rect;
1318 if (data->real_coordinates) {
1319 std::vector<std::string> v_geom = split(parts[1],',');
1321 if (v_geom.size() == 1)
1322 v_geom.emplace_back("1");
1324 MY_CHECKGEOM("dropdown",1);
1326 pos = getRealCoordinateBasePos(v_pos);
1327 geom = getRealCoordinateGeometry(v_geom);
1328 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1330 pos = getElementBasePos(&v_pos);
1332 s32 width = stof(parts[1]) * spacing.Y;
1334 rect = core::rect<s32>(pos.X, pos.Y,
1335 pos.X + width, pos.Y + (m_btn_height * 2));
1342 258 + m_fields.size()
1345 spec.ftype = f_DropDown;
1348 //now really show list
1349 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1352 if (spec.fname == m_focused_element) {
1353 Environment->setFocus(e);
1356 for (const std::string &item : items) {
1357 e->addItem(unescape_translate(unescape_string(
1358 utf8_to_wide(item))).c_str());
1361 if (!str_initial_selection.empty())
1362 e->setSelected(stoi(str_initial_selection)-1);
1364 auto style = getDefaultStyleForElement("dropdown", name);
1366 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1368 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1370 m_fields.push_back(spec);
1372 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1373 std::vector<std::string> &values = m_dropdowns.back().second;
1374 for (const std::string &item : items) {
1375 values.push_back(unescape_string(item));
1379 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1381 std::vector<std::string> parts;
1382 if (!precheckElement("field_close_on_enter", element, 2, 2, parts))
1385 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1388 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1390 std::vector<std::string> parts;
1391 if (!precheckElement("pwdfield", element, 4, 4, parts))
1394 std::vector<std::string> v_pos = split(parts[0],',');
1395 std::vector<std::string> v_geom = split(parts[1],',');
1396 std::string name = parts[2];
1397 std::string label = parts[3];
1399 MY_CHECKPOS("pwdfield",0);
1400 MY_CHECKGEOM("pwdfield",1);
1405 if (data->real_coordinates) {
1406 pos = getRealCoordinateBasePos(v_pos);
1407 geom = getRealCoordinateGeometry(v_geom);
1409 pos = getElementBasePos(&v_pos);
1412 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1414 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1415 pos.Y -= m_btn_height;
1416 geom.Y = m_btn_height*2;
1419 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1421 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1427 258 + m_fields.size(),
1433 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1434 data->current_parent, spec.fid);
1436 if (spec.fname == m_focused_element) {
1437 Environment->setFocus(e);
1440 if (label.length() >= 1) {
1441 int font_height = g_fontengine->getTextHeight();
1442 rect.UpperLeftCorner.Y -= font_height;
1443 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1444 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1445 data->current_parent, 0);
1448 e->setPasswordBox(true,L'*');
1450 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1451 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1452 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1453 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1454 e->setOverrideFont(style.getFont());
1457 evt.EventType = EET_KEY_INPUT_EVENT;
1458 evt.KeyInput.Key = KEY_END;
1459 evt.KeyInput.Char = 0;
1460 evt.KeyInput.Control = false;
1461 evt.KeyInput.Shift = false;
1462 evt.KeyInput.PressedDown = true;
1465 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1466 // warning referring to field_close_on_enter[]!
1468 m_fields.push_back(spec);
1471 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1472 core::rect<s32> &rect, bool is_multiline)
1474 bool is_editable = !spec.fname.empty();
1475 if (!is_editable && !is_multiline) {
1476 // spec field id to 0, this stops submit searching for a value that isn't there
1477 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1478 data->current_parent, 0);
1484 } else if (is_multiline &&
1485 spec.fdefault.empty() && !spec.flabel.empty()) {
1486 // Multiline textareas: swap default and label for backwards compat
1487 spec.flabel.swap(spec.fdefault);
1490 gui::IGUIEditBox *e = nullptr;
1492 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1493 data->current_parent, spec.fid, rect, is_editable, true);
1494 } else if (is_editable) {
1495 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1496 data->current_parent, spec.fid);
1500 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1503 if (is_editable && spec.fname == m_focused_element)
1504 Environment->setFocus(e);
1507 e->setMultiLine(true);
1508 e->setWordWrap(true);
1509 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1512 evt.EventType = EET_KEY_INPUT_EVENT;
1513 evt.KeyInput.Key = KEY_END;
1514 evt.KeyInput.Char = 0;
1515 evt.KeyInput.Control = 0;
1516 evt.KeyInput.Shift = 0;
1517 evt.KeyInput.PressedDown = true;
1521 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1522 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1523 bool border = style.getBool(StyleSpec::BORDER, true);
1524 e->setDrawBorder(border);
1525 e->setDrawBackground(border);
1526 e->setOverrideFont(style.getFont());
1531 if (!spec.flabel.empty()) {
1532 int font_height = g_fontengine->getTextHeight();
1533 rect.UpperLeftCorner.Y -= font_height;
1534 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1535 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1536 rect, false, true, data->current_parent, 0);
1539 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1543 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1544 std::vector<std::string> &parts)
1546 std::string name = parts[0];
1547 std::string label = parts[1];
1548 std::string default_val = parts[2];
1550 core::rect<s32> rect;
1552 if (data->explicit_size)
1553 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1555 v2s32 pos = getElementBasePos(nullptr);
1556 pos.Y = (data->simple_field_count + 2) * 60;
1557 v2s32 size = DesiredRect.getSize();
1559 rect = core::rect<s32>(
1560 size.X / 2 - 150, pos.Y,
1561 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1566 default_val = m_form_src->resolveText(default_val);
1569 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1574 utf8_to_wide(unescape_string(default_val)),
1575 258 + m_fields.size(),
1580 createTextField(data, spec, rect, false);
1582 m_fields.push_back(spec);
1584 data->simple_field_count++;
1587 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1588 const std::string &type)
1590 std::vector<std::string> v_pos = split(parts[0],',');
1591 std::vector<std::string> v_geom = split(parts[1],',');
1592 std::string name = parts[2];
1593 std::string label = parts[3];
1594 std::string default_val = parts[4];
1596 MY_CHECKPOS(type,0);
1597 MY_CHECKGEOM(type,1);
1602 if (data->real_coordinates) {
1603 pos = getRealCoordinateBasePos(v_pos);
1604 geom = getRealCoordinateGeometry(v_geom);
1606 pos = getElementBasePos(&v_pos);
1609 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1611 if (type == "textarea")
1613 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1614 pos.Y += m_btn_height;
1618 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1619 pos.Y -= m_btn_height;
1620 geom.Y = m_btn_height*2;
1624 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1626 if(!data->explicit_size)
1627 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1630 default_val = m_form_src->resolveText(default_val);
1633 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1638 utf8_to_wide(unescape_string(default_val)),
1639 258 + m_fields.size(),
1644 createTextField(data, spec, rect, type == "textarea");
1646 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1647 // warning referring to field_close_on_enter[]!
1649 m_fields.push_back(spec);
1652 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1653 const std::string &type)
1655 std::vector<std::string> parts;
1656 if (!precheckElement(type, element, 3, 5, parts))
1659 if (parts.size() == 3 || parts.size() == 4) {
1660 parseSimpleField(data, parts);
1664 // Else: >= 5 arguments in "parts"
1665 parseTextArea(data, parts, type);
1668 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1670 MY_CHECKCLIENT("list");
1672 std::vector<std::string> parts;
1673 if (!precheckElement("hypertext", element, 4, 4, parts))
1676 std::vector<std::string> v_pos = split(parts[0], ',');
1677 std::vector<std::string> v_geom = split(parts[1], ',');
1678 std::string name = parts[2];
1679 std::string text = parts[3];
1681 MY_CHECKPOS("hypertext", 0);
1682 MY_CHECKGEOM("hypertext", 1);
1687 if (data->real_coordinates) {
1688 pos = getRealCoordinateBasePos(v_pos);
1689 geom = getRealCoordinateGeometry(v_geom);
1691 pos = getElementBasePos(&v_pos);
1694 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1695 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1696 pos.Y += m_btn_height;
1699 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1702 text = m_form_src->resolveText(text);
1706 translate_string(utf8_to_wide(unescape_string(text))),
1708 258 + m_fields.size()
1711 spec.ftype = f_HyperText;
1713 auto style = getDefaultStyleForElement("hypertext", spec.fname);
1714 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1716 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1717 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1720 m_fields.push_back(spec);
1723 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1725 std::vector<std::string> parts;
1726 if (!precheckElement("label", element, 2, 2, parts))
1729 std::vector<std::string> v_pos = split(parts[0],',');
1730 std::string text = parts[1];
1732 MY_CHECKPOS("label",0);
1734 if(!data->explicit_size)
1735 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1737 std::vector<std::string> lines = split(text, '\n');
1739 auto style = getDefaultStyleForElement("label", "");
1740 gui::IGUIFont *font = style.getFont();
1744 for (unsigned int i = 0; i != lines.size(); i++) {
1745 std::wstring wlabel_colors = translate_string(
1746 utf8_to_wide(unescape_string(lines[i])));
1747 // Without color escapes to get the font dimensions
1748 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1750 core::rect<s32> rect;
1752 if (data->real_coordinates) {
1753 // Lines are spaced at the distance of 1/2 imgsize.
1754 // This alows lines that line up with the new elements
1755 // easily without sacrificing good line distance. If
1756 // it was one whole imgsize, it would have too much
1758 v2s32 pos = getRealCoordinateBasePos(v_pos);
1760 // Labels are positioned by their center, not their top.
1761 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1763 rect = core::rect<s32>(
1765 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1769 // Lines are spaced at the nominal distance of
1770 // 2/5 inventory slot, even if the font doesn't
1771 // quite match that. This provides consistent
1772 // form layout, at the expense of sometimes
1773 // having sub-optimal spacing for the font.
1774 // We multiply by 2 and then divide by 5, rather
1775 // than multiply by 0.4, to get exact results
1776 // in the integer cases: 0.4 is not exactly
1777 // representable in binary floating point.
1779 v2s32 pos = getElementBasePos(nullptr);
1780 pos.X += stof(v_pos[0]) * spacing.X;
1781 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1783 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1785 rect = core::rect<s32>(
1786 pos.X, pos.Y - m_btn_height,
1787 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1788 pos.Y + m_btn_height);
1795 258 + m_fields.size(),
1798 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1799 spec.flabel.c_str(), rect, false, false, data->current_parent,
1801 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1803 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1804 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1805 e->setOverrideFont(font);
1807 m_fields.push_back(spec);
1809 // labels should let events through
1811 m_clickthrough_elements.push_back(e);
1815 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1817 std::vector<std::string> parts;
1818 if (!precheckElement("vertlabel", element, 2, 2, parts))
1821 std::vector<std::string> v_pos = split(parts[0],',');
1822 std::wstring text = unescape_translate(
1823 unescape_string(utf8_to_wide(parts[1])));
1825 MY_CHECKPOS("vertlabel",1);
1827 auto style = getDefaultStyleForElement("vertlabel", "", "label");
1828 gui::IGUIFont *font = style.getFont();
1833 core::rect<s32> rect;
1835 if (data->real_coordinates) {
1836 pos = getRealCoordinateBasePos(v_pos);
1838 // Vertlabels are positioned by center, not left.
1839 pos.X -= imgsize.X / 2;
1841 // We use text.length + 1 because without it, the rect
1842 // isn't quite tall enough and cuts off the text.
1843 rect = core::rect<s32>(pos.X, pos.Y,
1845 pos.Y + font_line_height(font) *
1846 (text.length() + 1));
1849 pos = getElementBasePos(&v_pos);
1851 // As above, the length must be one longer. The width of
1852 // the rect (15 pixels) seems rather arbitrary, but
1853 // changing it might break something.
1854 rect = core::rect<s32>(
1855 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1857 font_line_height(font) *
1858 (text.length() + 1) +
1859 ((imgsize.Y/2) - m_btn_height));
1862 if(!data->explicit_size)
1863 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1867 for (wchar_t i : text) {
1876 258 + m_fields.size()
1878 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1879 rect, false, false, data->current_parent, spec.fid);
1880 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1882 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1883 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1884 e->setOverrideFont(font);
1886 m_fields.push_back(spec);
1888 // vertlabels should let events through
1890 m_clickthrough_elements.push_back(e);
1893 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1894 const std::string &type)
1896 std::vector<std::string> parts;
1897 if (!precheckElement("image_button", element, 5, 8, parts))
1900 if (parts.size() == 6) {
1901 // Invalid argument count.
1902 errorstream << "Invalid image_button element(" << parts.size() << "): '" << element << "'" << std::endl;
1906 std::vector<std::string> v_pos = split(parts[0],',');
1907 std::vector<std::string> v_geom = split(parts[1],',');
1908 std::string image_name = parts[2];
1909 std::string name = parts[3];
1910 std::string label = parts[4];
1912 MY_CHECKPOS("image_button",0);
1913 MY_CHECKGEOM("image_button",1);
1915 std::string pressed_image_name;
1917 if (parts.size() >= 8) {
1918 pressed_image_name = parts[7];
1924 if (data->real_coordinates) {
1925 pos = getRealCoordinateBasePos(v_pos);
1926 geom = getRealCoordinateGeometry(v_geom);
1928 pos = getElementBasePos(&v_pos);
1929 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1930 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1933 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1936 if (!data->explicit_size)
1937 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1939 image_name = unescape_string(image_name);
1940 pressed_image_name = unescape_string(pressed_image_name);
1942 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1947 utf8_to_wide(image_name),
1948 258 + m_fields.size()
1950 spec.ftype = f_Button;
1951 if (type == "image_button_exit")
1952 spec.is_exit = true;
1954 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1955 data->current_parent, spec.fid, spec.flabel.c_str());
1957 if (spec.fname == m_focused_element) {
1958 Environment->setFocus(e);
1961 auto style = getStyleForElement("image_button", spec.fname);
1963 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1965 // Override style properties with values specified directly in the element
1966 if (!image_name.empty())
1967 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1969 if (!pressed_image_name.empty())
1970 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
1972 if (parts.size() >= 7) {
1973 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
1974 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
1977 e->setStyles(style);
1978 e->setScaleImage(true);
1980 m_fields.push_back(spec);
1983 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1985 std::vector<std::string> parts;
1986 if (!precheckElement("tabheader", element, 4, 7, parts))
1989 // Length 7: Additional "height" parameter after "pos". Only valid with real_coordinates.
1990 // Note: New arguments for the "height" syntax cannot be added without breaking older clients.
1991 if (parts.size() == 5 || (parts.size() == 7 && !data->real_coordinates)) {
1992 errorstream << "Invalid tabheader element(" << parts.size() << "): '"
1993 << element << "'" << std::endl;
1997 std::vector<std::string> v_pos = split(parts[0],',');
1999 // If we're using real coordinates, add an extra field for height.
2000 // Width is not here because tabs are the width of the text, and
2001 // there's no reason to change that.
2003 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2004 bool auto_width = true;
2005 if (parts.size() == 7) {
2008 v_geom = split(parts[1], ',');
2009 if (v_geom.size() == 1)
2010 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2015 std::string name = parts[i+1];
2016 std::vector<std::string> buttons = split(parts[i+2], ',');
2017 std::string str_index = parts[i+3];
2018 bool show_background = true;
2019 bool show_border = true;
2020 int tab_index = stoi(str_index) - 1;
2022 MY_CHECKPOS("tabheader", 0);
2024 if (parts.size() == 6 + i) {
2025 if (parts[4+i] == "true")
2026 show_background = false;
2027 if (parts[5+i] == "false")
2028 show_border = false;
2035 258 + m_fields.size()
2038 spec.ftype = f_TabHeader;
2043 if (data->real_coordinates) {
2044 pos = getRealCoordinateBasePos(v_pos);
2046 geom = getRealCoordinateGeometry(v_geom);
2047 // Set default height
2048 if (parts.size() <= 6)
2049 geom.Y = m_btn_height * 2;
2050 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2052 geom.X = DesiredRect.getWidth(); // Set automatic width
2054 MY_CHECKGEOM("tabheader", 1);
2056 v2f32 pos_f = pos_offset * spacing;
2057 pos_f.X += stof(v_pos[0]) * spacing.X;
2058 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2059 pos = v2s32(pos_f.X, pos_f.Y);
2061 geom.Y = m_btn_height * 2;
2062 geom.X = DesiredRect.getWidth();
2065 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2068 gui::IGUITabControl *e = Environment->addTabControl(rect,
2069 data->current_parent, show_background, show_border, spec.fid);
2070 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2071 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2072 e->setTabHeight(geom.Y);
2074 auto style = getDefaultStyleForElement("tabheader", name);
2076 spec.sound = style.get(StyleSpec::Property::SOUND, "");
2078 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2080 for (const std::string &button : buttons) {
2081 auto tab = e->addTab(unescape_translate(unescape_string(
2082 utf8_to_wide(button))).c_str(), -1);
2083 if (style.isNotDefault(StyleSpec::BGCOLOR))
2084 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2086 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2089 if ((tab_index >= 0) &&
2090 (buttons.size() < INT_MAX) &&
2091 (tab_index < (int) buttons.size()))
2092 e->setActiveTab(tab_index);
2094 m_fields.push_back(spec);
2097 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2099 MY_CHECKCLIENT("item_image_button");
2101 std::vector<std::string> parts;
2102 if (!precheckElement("item_image_button", element, 5, 5, parts))
2105 std::vector<std::string> v_pos = split(parts[0],',');
2106 std::vector<std::string> v_geom = split(parts[1],',');
2107 std::string item_name = parts[2];
2108 std::string name = parts[3];
2109 std::string label = parts[4];
2111 label = unescape_string(label);
2112 item_name = unescape_string(item_name);
2114 MY_CHECKPOS("item_image_button",0);
2115 MY_CHECKGEOM("item_image_button",1);
2120 if (data->real_coordinates) {
2121 pos = getRealCoordinateBasePos(v_pos);
2122 geom = getRealCoordinateGeometry(v_geom);
2124 pos = getElementBasePos(&v_pos);
2125 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2126 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2129 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2131 if(!data->explicit_size)
2132 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2134 IItemDefManager *idef = m_client->idef();
2136 item.deSerialize(item_name, idef);
2139 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2140 m_default_tooltip_bgcolor,
2141 m_default_tooltip_color);
2143 // the spec for the button
2146 utf8_to_wide(label),
2147 utf8_to_wide(item_name),
2148 258 + m_fields.size(),
2152 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2153 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2154 item_name, m_client);
2156 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2158 spec_btn.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
2160 e_btn->setStyles(style);
2162 if (spec_btn.fname == m_focused_element) {
2163 Environment->setFocus(e_btn);
2166 spec_btn.ftype = f_Button;
2167 rect += data->basepos-padding;
2168 spec_btn.rect = rect;
2169 m_fields.push_back(spec_btn);
2172 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2174 std::vector<std::string> parts;
2175 if (!precheckElement("box", element, 3, 3, parts))
2178 std::vector<std::string> v_pos = split(parts[0], ',');
2179 std::vector<std::string> v_geom = split(parts[1], ',');
2181 MY_CHECKPOS("box", 0);
2182 MY_CHECKGEOM("box", 1);
2187 if (data->real_coordinates) {
2188 pos = getRealCoordinateBasePos(v_pos);
2189 geom = getRealCoordinateGeometry(v_geom);
2191 pos = getElementBasePos(&v_pos);
2192 geom.X = stof(v_geom[0]) * spacing.X;
2193 geom.Y = stof(v_geom[1]) * spacing.Y;
2200 258 + m_fields.size(),
2205 auto style = getDefaultStyleForElement("box", spec.fname);
2207 video::SColor tmp_color;
2208 std::array<video::SColor, 4> colors;
2209 std::array<video::SColor, 4> bordercolors = {0x0, 0x0, 0x0, 0x0};
2210 std::array<s32, 4> borderwidths = {0, 0, 0, 0};
2212 if (parseColorString(parts[2], tmp_color, true, 0x8C)) {
2213 colors = {tmp_color, tmp_color, tmp_color, tmp_color};
2215 colors = style.getColorArray(StyleSpec::COLORS, {0x0, 0x0, 0x0, 0x0});
2216 bordercolors = style.getColorArray(StyleSpec::BORDERCOLORS,
2217 {0x0, 0x0, 0x0, 0x0});
2218 borderwidths = style.getIntArray(StyleSpec::BORDERWIDTHS, {0, 0, 0, 0});
2221 core::rect<s32> rect(pos, pos + geom);
2223 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid, rect,
2224 colors, bordercolors, borderwidths);
2225 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2228 m_fields.push_back(spec);
2231 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2233 std::vector<std::string> parts;
2234 if (!precheckElement("bgcolor", element, 1, 3, parts))
2237 const u32 parameter_count = parts.size();
2239 if (parameter_count > 2 && m_formspec_version < 3) {
2240 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2241 << element << "'" << std::endl;
2246 if (parameter_count >= 1 && parts[0] != "")
2247 parseColorString(parts[0], m_bgcolor, false);
2250 if (parameter_count >= 2) {
2251 if (parts[1] == "both") {
2252 m_bgnonfullscreen = true;
2253 m_bgfullscreen = true;
2254 } else if (parts[1] == "neither") {
2255 m_bgnonfullscreen = false;
2256 m_bgfullscreen = false;
2257 } else if (parts[1] != "" || m_formspec_version < 3) {
2258 m_bgfullscreen = is_yes(parts[1]);
2259 m_bgnonfullscreen = !m_bgfullscreen;
2264 if (parameter_count >= 3 && parts[2] != "")
2265 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2268 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2270 std::vector<std::string> parts;
2271 // Legacy Note: If clients older than 5.5.0-dev are supplied with additional arguments,
2272 // the tooltip colors will be ignored.
2273 if (!precheckElement("listcolors", element, 2, 5, parts))
2276 if (parts.size() == 4) {
2277 // Invalid argument combination
2278 errorstream << "Invalid listcolors element(" << parts.size() << "): '"
2279 << element << "'" << std::endl;
2283 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2284 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2286 if (parts.size() >= 3) {
2287 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2289 data->inventorylist_options.slotborder = true;
2292 if (parts.size() >= 5) {
2293 video::SColor tmp_color;
2295 if (parseColorString(parts[3], tmp_color, false))
2296 m_default_tooltip_bgcolor = tmp_color;
2297 if (parseColorString(parts[4], tmp_color, false))
2298 m_default_tooltip_color = tmp_color;
2301 // update all already parsed inventorylists
2302 for (GUIInventoryList *e : m_inventorylists) {
2303 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2304 data->inventorylist_options.slotbg_h);
2305 e->setSlotBorders(data->inventorylist_options.slotborder,
2306 data->inventorylist_options.slotbordercolor);
2310 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2312 std::vector<std::string> parts;
2313 if (!precheckElement("tooltip", element, 2, 5, parts))
2316 // Get mode and check size
2317 bool rect_mode = parts[0].find(',') != std::string::npos;
2318 size_t base_size = rect_mode ? 3 : 2;
2319 if (parts.size() != base_size && parts.size() != base_size + 2) {
2320 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2321 << element << "'" << std::endl;
2326 video::SColor bgcolor = m_default_tooltip_bgcolor;
2327 video::SColor color = m_default_tooltip_color;
2328 if (parts.size() == base_size + 2 &&
2329 (!parseColorString(parts[base_size], bgcolor, false) ||
2330 !parseColorString(parts[base_size + 1], color, false))) {
2331 errorstream << "Invalid color in tooltip element(" << parts.size()
2332 << "): '" << element << "'" << std::endl;
2336 // Make tooltip spec
2337 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2338 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2342 std::vector<std::string> v_pos = split(parts[0], ',');
2343 std::vector<std::string> v_geom = split(parts[1], ',');
2345 MY_CHECKPOS("tooltip", 0);
2346 MY_CHECKGEOM("tooltip", 1);
2351 if (data->real_coordinates) {
2352 pos = getRealCoordinateBasePos(v_pos);
2353 geom = getRealCoordinateGeometry(v_geom);
2355 pos = getElementBasePos(&v_pos);
2356 geom.X = stof(v_geom[0]) * spacing.X;
2357 geom.Y = stof(v_geom[1]) * spacing.Y;
2360 FieldSpec fieldspec(
2364 258 + m_fields.size()
2367 core::rect<s32> rect(pos, pos + geom);
2369 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2370 data->current_parent, fieldspec.fid, rect);
2372 // the element the rect tooltip is bound to should not block mouse-clicks
2373 e->setVisible(false);
2375 m_fields.push_back(fieldspec);
2376 m_tooltip_rects.emplace_back(e, spec);
2379 m_tooltips[parts[0]] = spec;
2383 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2389 std::vector<std::string> parts = split(data,'[');
2391 if (parts.size() < 2) {
2395 if (trim(parts[0]) != "formspec_version") {
2399 if (is_number(parts[1])) {
2400 m_formspec_version = mystoi(parts[1]);
2407 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2409 if (element.empty())
2412 std::vector<std::string> parts = split(element,'[');
2414 if (parts.size() < 2)
2417 std::string type = trim(parts[0]);
2418 std::string description = trim(parts[1]);
2420 if (type != "size" && type != "invsize")
2423 if (type == "invsize")
2424 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2426 parseSize(data, description);
2431 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2433 if (element.empty())
2436 std::vector<std::string> parts = split(element, '[');
2438 if (parts.size() != 2)
2441 std::string type = trim(parts[0]);
2442 std::string description = trim(parts[1]);
2444 if (type != "position")
2447 parsePosition(data, description);
2452 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2454 std::vector<std::string> parts = split(element, ';');
2456 if (parts.size() == 1 ||
2457 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2458 std::vector<std::string> v_geom = split(parts[0], ',');
2460 MY_CHECKGEOM("position", 0);
2462 data->offset.X = stof(v_geom[0]);
2463 data->offset.Y = stof(v_geom[1]);
2467 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2470 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2472 if (element.empty())
2475 std::vector<std::string> parts = split(element, '[');
2477 if (parts.size() != 2)
2480 std::string type = trim(parts[0]);
2481 std::string description = trim(parts[1]);
2483 if (type != "anchor")
2486 parseAnchor(data, description);
2491 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2493 std::vector<std::string> parts = split(element, ';');
2495 if (parts.size() == 1 ||
2496 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2497 std::vector<std::string> v_geom = split(parts[0], ',');
2499 MY_CHECKGEOM("anchor", 0);
2501 data->anchor.X = stof(v_geom[0]);
2502 data->anchor.Y = stof(v_geom[1]);
2506 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2507 << "'" << std::endl;
2510 bool GUIFormSpecMenu::parsePaddingDirect(parserData *data, const std::string &element)
2512 if (element.empty())
2515 std::vector<std::string> parts = split(element, '[');
2517 if (parts.size() != 2)
2520 std::string type = trim(parts[0]);
2521 std::string description = trim(parts[1]);
2523 if (type != "padding")
2526 parsePadding(data, description);
2531 void GUIFormSpecMenu::parsePadding(parserData *data, const std::string &element)
2533 std::vector<std::string> parts = split(element, ';');
2535 if (parts.size() == 1 ||
2536 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2537 std::vector<std::string> v_geom = split(parts[0], ',');
2539 MY_CHECKGEOM("padding", 0);
2541 data->padding.X = stof(v_geom[0]);
2542 data->padding.Y = stof(v_geom[1]);
2546 errorstream << "Invalid padding element (" << parts.size() << "): '" << element
2547 << "'" << std::endl;
2550 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2552 std::vector<std::string> parts = split(element, ';');
2554 if (parts.size() < 2) {
2555 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2556 << "'" << std::endl;
2563 for (size_t i = 1; i < parts.size(); i++) {
2564 size_t equal_pos = parts[i].find('=');
2565 if (equal_pos == std::string::npos) {
2566 errorstream << "Invalid style element (Property missing value): '" << element
2567 << "'" << std::endl;
2571 std::string propname = trim(parts[i].substr(0, equal_pos));
2572 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2574 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2576 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2577 if (prop == StyleSpec::NONE) {
2578 if (property_warned.find(propname) != property_warned.end()) {
2579 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2581 << "'" << std::endl;
2582 property_warned.insert(propname);
2587 spec.set(prop, value);
2590 std::vector<std::string> selectors = split(parts[0], ',');
2591 for (size_t sel = 0; sel < selectors.size(); sel++) {
2592 std::string selector = trim(selectors[sel]);
2594 // Copy the style properties to a new StyleSpec
2595 // This allows a separate state mask per-selector
2596 StyleSpec selector_spec = spec;
2598 // Parse state information, if it exists
2599 bool state_valid = true;
2600 size_t state_pos = selector.find(':');
2601 if (state_pos != std::string::npos) {
2602 std::string state_str = selector.substr(state_pos + 1);
2603 selector = selector.substr(0, state_pos);
2605 if (state_str.empty()) {
2606 errorstream << "Invalid style element (Invalid state): '" << element
2607 << "'" << std::endl;
2608 state_valid = false;
2610 std::vector<std::string> states = split(state_str, '+');
2611 for (std::string &state : states) {
2612 StyleSpec::State converted = StyleSpec::getStateByName(state);
2613 if (converted == StyleSpec::STATE_INVALID) {
2614 infostream << "Unknown style state " << state <<
2615 " in element '" << element << "'" << std::endl;
2616 state_valid = false;
2620 selector_spec.addState(converted);
2626 // Skip this selector
2631 theme_by_type[selector].push_back(selector_spec);
2633 theme_by_name[selector].push_back(selector_spec);
2636 // Backwards-compatibility for existing _hovered/_pressed properties
2637 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2638 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2639 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2640 StyleSpec hover_spec;
2641 hover_spec.addState(StyleSpec::STATE_HOVERED);
2643 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2644 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2646 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2647 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2649 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2650 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2654 theme_by_type[selector].push_back(hover_spec);
2656 theme_by_name[selector].push_back(hover_spec);
2659 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2660 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2661 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2662 StyleSpec press_spec;
2663 press_spec.addState(StyleSpec::STATE_PRESSED);
2665 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2666 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2668 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2669 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2671 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2672 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2676 theme_by_type[selector].push_back(press_spec);
2678 theme_by_name[selector].push_back(press_spec);
2686 void GUIFormSpecMenu::parseSetFocus(const std::string &element)
2688 std::vector<std::string> parts;
2689 if (!precheckElement("set_focus", element, 1, 2, parts))
2692 if (m_is_form_regenerated)
2693 return; // Never focus on resizing
2695 bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
2696 if (force_focus || m_text_dst->m_formname != m_last_formname)
2700 void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element)
2702 MY_CHECKCLIENT("model");
2704 std::vector<std::string> parts;
2705 if (!precheckElement("model", element, 5, 10, parts))
2708 // Avoid length checks by resizing
2709 if (parts.size() < 10)
2712 std::vector<std::string> v_pos = split(parts[0], ',');
2713 std::vector<std::string> v_geom = split(parts[1], ',');
2714 std::string name = unescape_string(parts[2]);
2715 std::string meshstr = unescape_string(parts[3]);
2716 std::vector<std::string> textures = split(parts[4], ',');
2717 std::vector<std::string> vec_rot = split(parts[5], ',');
2718 bool inf_rotation = is_yes(parts[6]);
2719 bool mousectrl = is_yes(parts[7]) || parts[7].empty(); // default true
2720 std::vector<std::string> frame_loop = split(parts[8], ',');
2721 std::string speed = unescape_string(parts[9]);
2723 MY_CHECKPOS("model", 0);
2724 MY_CHECKGEOM("model", 1);
2729 if (data->real_coordinates) {
2730 pos = getRealCoordinateBasePos(v_pos);
2731 geom = getRealCoordinateGeometry(v_geom);
2733 pos = getElementBasePos(&v_pos);
2734 geom.X = stof(v_geom[0]) * (float)imgsize.X;
2735 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
2738 if (!data->explicit_size)
2739 warningstream << "invalid use of model without a size[] element" << std::endl;
2741 scene::IAnimatedMesh *mesh = m_client->getMesh(meshstr);
2744 errorstream << "Invalid model element: Unable to load mesh:"
2745 << std::endl << "\t" << meshstr << std::endl;
2753 258 + m_fields.size()
2756 core::rect<s32> rect(pos, pos + geom);
2758 GUIScene *e = new GUIScene(Environment, m_client->getSceneManager(),
2759 data->current_parent, rect, spec.fid);
2761 auto meshnode = e->setMesh(mesh);
2763 for (u32 i = 0; i < textures.size() && i < meshnode->getMaterialCount(); ++i)
2764 e->setTexture(i, m_tsrc->getTexture(unescape_string(textures[i])));
2766 if (vec_rot.size() >= 2)
2767 e->setRotation(v2f(stof(vec_rot[0]), stof(vec_rot[1])));
2769 e->enableContinuousRotation(inf_rotation);
2770 e->enableMouseControl(mousectrl);
2772 s32 frame_loop_begin = 0;
2773 s32 frame_loop_end = 0x7FFFFFFF;
2775 if (frame_loop.size() == 2) {
2776 frame_loop_begin = stoi(frame_loop[0]);
2777 frame_loop_end = stoi(frame_loop[1]);
2780 e->setFrameLoop(frame_loop_begin, frame_loop_end);
2781 e->setAnimationSpeed(stof(speed));
2783 auto style = getStyleForElement("model", spec.fname);
2784 e->setStyles(style);
2787 m_fields.push_back(spec);
2790 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2793 if (element.empty())
2796 if (parseVersionDirect(element))
2799 size_t pos = element.find('[');
2800 if (pos == std::string::npos)
2803 std::string type = trim(element.substr(0, pos));
2804 std::string description = element.substr(pos+1);
2806 if (type == "container") {
2807 parseContainer(data, description);
2811 if (type == "container_end") {
2812 parseContainerEnd(data);
2816 if (type == "list") {
2817 parseList(data, description);
2821 if (type == "listring") {
2822 parseListRing(data, description);
2826 if (type == "checkbox") {
2827 parseCheckbox(data, description);
2831 if (type == "image") {
2832 parseImage(data, description);
2836 if (type == "animated_image") {
2837 parseAnimatedImage(data, description);
2841 if (type == "item_image") {
2842 parseItemImage(data, description);
2846 if (type == "button" || type == "button_exit") {
2847 parseButton(data, description, type);
2851 if (type == "background" || type == "background9") {
2852 parseBackground(data, description);
2856 if (type == "tableoptions"){
2857 parseTableOptions(data,description);
2861 if (type == "tablecolumns"){
2862 parseTableColumns(data,description);
2866 if (type == "table"){
2867 parseTable(data,description);
2871 if (type == "textlist"){
2872 parseTextList(data,description);
2876 if (type == "dropdown"){
2877 parseDropDown(data,description);
2881 if (type == "field_close_on_enter") {
2882 parseFieldCloseOnEnter(data, description);
2886 if (type == "pwdfield") {
2887 parsePwdField(data,description);
2891 if ((type == "field") || (type == "textarea")){
2892 parseField(data,description,type);
2896 if (type == "hypertext") {
2897 parseHyperText(data,description);
2901 if (type == "label") {
2902 parseLabel(data,description);
2906 if (type == "vertlabel") {
2907 parseVertLabel(data,description);
2911 if (type == "item_image_button") {
2912 parseItemImageButton(data,description);
2916 if ((type == "image_button") || (type == "image_button_exit")) {
2917 parseImageButton(data,description,type);
2921 if (type == "tabheader") {
2922 parseTabHeader(data,description);
2926 if (type == "box") {
2927 parseBox(data,description);
2931 if (type == "bgcolor") {
2932 parseBackgroundColor(data,description);
2936 if (type == "listcolors") {
2937 parseListColors(data,description);
2941 if (type == "tooltip") {
2942 parseTooltip(data,description);
2946 if (type == "scrollbar") {
2947 parseScrollBar(data, description);
2951 if (type == "real_coordinates") {
2952 data->real_coordinates = is_yes(description);
2956 if (type == "style") {
2957 parseStyle(data, description, false);
2961 if (type == "style_type") {
2962 parseStyle(data, description, true);
2966 if (type == "scrollbaroptions") {
2967 parseScrollBarOptions(data, description);
2971 if (type == "scroll_container") {
2972 parseScrollContainer(data, description);
2976 if (type == "scroll_container_end") {
2977 parseScrollContainerEnd(data);
2981 if (type == "set_focus") {
2982 parseSetFocus(description);
2986 if (type == "model") {
2987 parseModel(data, description);
2992 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2996 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2998 // Useless to regenerate without a screensize
2999 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
3005 // Preserve stuff only on same form, not on a new form.
3006 if (m_text_dst->m_formname == m_last_formname) {
3007 // Preserve tables/textlists
3008 for (auto &m_table : m_tables) {
3009 std::string tablename = m_table.first.fname;
3010 GUITable *table = m_table.second;
3011 mydata.table_dyndata[tablename] = table->getDynamicData();
3015 gui::IGUIElement *focused_element = Environment->getFocus();
3016 if (focused_element && focused_element->getParent() == this) {
3017 s32 focused_id = focused_element->getID();
3018 if (focused_id > 257) {
3019 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
3020 if (field.fid == focused_id) {
3021 m_focused_element = field.fname;
3028 // Don't keep old focus value
3029 m_focused_element = "";
3033 removeAllChildren();
3036 for (auto &table_it : m_tables)
3037 table_it.second->drop();
3038 for (auto &inventorylist_it : m_inventorylists)
3039 inventorylist_it->drop();
3040 for (auto &checkbox_it : m_checkboxes)
3041 checkbox_it.second->drop();
3042 for (auto &scrollbar_it : m_scrollbars)
3043 scrollbar_it.second->drop();
3044 for (auto &tooltip_rect_it : m_tooltip_rects)
3045 tooltip_rect_it.first->drop();
3046 for (auto &clickthrough_it : m_clickthrough_elements)
3047 clickthrough_it->drop();
3048 for (auto &scroll_container_it : m_scroll_containers)
3049 scroll_container_it.second->drop();
3051 mydata.size = v2s32(100, 100);
3052 mydata.screensize = screensize;
3053 mydata.offset = v2f32(0.5f, 0.5f);
3054 mydata.anchor = v2f32(0.5f, 0.5f);
3055 mydata.padding = v2f32(0.05f, 0.05f);
3056 mydata.simple_field_count = 0;
3058 // Base position of contents of form
3059 mydata.basepos = getBasePos();
3061 // the parent for the parsed elements
3062 mydata.current_parent = this;
3064 m_inventorylists.clear();
3066 m_checkboxes.clear();
3067 m_scrollbars.clear();
3070 m_tooltip_rects.clear();
3071 m_inventory_rings.clear();
3072 m_dropdowns.clear();
3073 m_scroll_containers.clear();
3074 theme_by_name.clear();
3075 theme_by_type.clear();
3076 m_clickthrough_elements.clear();
3077 field_close_on_enter.clear();
3078 m_dropdown_index_event.clear();
3080 m_bgnonfullscreen = true;
3081 m_bgfullscreen = false;
3083 m_formspec_version = 1;
3086 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
3087 m_bgcolor = video::SColor(
3088 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
3089 clamp_u8(myround(formspec_bgcolor.X)),
3090 clamp_u8(myround(formspec_bgcolor.Y)),
3091 clamp_u8(myround(formspec_bgcolor.Z))
3096 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
3097 m_fullscreen_bgcolor = video::SColor(
3098 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
3099 clamp_u8(myround(formspec_bgcolor.X)),
3100 clamp_u8(myround(formspec_bgcolor.Y)),
3101 clamp_u8(myround(formspec_bgcolor.Z))
3105 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3106 m_default_tooltip_color = video::SColor(255,255,255,255);
3110 assert(!m_tooltip_element);
3111 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3112 m_tooltip_element = gui::StaticText::add(Environment, L"",
3113 core::rect<s32>(0, 0, 110, 18));
3114 m_tooltip_element->enableOverrideColor(true);
3115 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3116 m_tooltip_element->setDrawBackground(true);
3117 m_tooltip_element->setDrawBorder(true);
3118 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3119 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3120 m_tooltip_element->setWordWrap(false);
3121 //we're not parent so no autograb for this one!
3122 m_tooltip_element->grab();
3125 std::vector<std::string> elements = split(m_formspec_string,']');
3128 /* try to read version from first element only */
3129 if (!elements.empty()) {
3130 if (parseVersionDirect(elements[0])) {
3135 /* we need size first in order to calculate image scale */
3136 mydata.explicit_size = false;
3137 for (; i< elements.size(); i++) {
3138 if (!parseSizeDirect(&mydata, elements[i])) {
3143 /* "position" element is always after "size" element if it used */
3144 for (; i< elements.size(); i++) {
3145 if (!parsePositionDirect(&mydata, elements[i])) {
3150 /* "anchor" element is always after "position" (or "size" element) if it used */
3151 for (; i< elements.size(); i++) {
3152 if (!parseAnchorDirect(&mydata, elements[i])) {
3157 /* "padding" element is always after "anchor" and previous if it is used */
3158 for (; i < elements.size(); i++) {
3159 if (!parsePaddingDirect(&mydata, elements[i])) {
3164 /* "no_prepend" element is always after "padding" and previous if it used */
3165 bool enable_prepends = true;
3166 for (; i < elements.size(); i++) {
3167 if (elements[i].empty())
3170 std::vector<std::string> parts = split(elements[i], '[');
3171 if (trim(parts[0]) == "no_prepend")
3172 enable_prepends = false;
3177 /* Copy of the "real_coordinates" element for after the form size. */
3178 mydata.real_coordinates = m_formspec_version >= 2;
3179 for (; i < elements.size(); i++) {
3180 std::vector<std::string> parts = split(elements[i], '[');
3181 std::string name = trim(parts[0]);
3182 if (name != "real_coordinates" || parts.size() != 2)
3183 break; // Invalid format
3185 mydata.real_coordinates = is_yes(trim(parts[1]));
3188 if (mydata.explicit_size) {
3189 // compute scaling for specified form size
3191 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3192 v2u32 delta = current_screensize - m_lockscreensize;
3194 if (current_screensize.Y > m_lockscreensize.Y)
3199 if (current_screensize.X > m_lockscreensize.X)
3204 offset = v2s32(delta.X,delta.Y);
3206 mydata.screensize = m_lockscreensize;
3208 offset = v2s32(0,0);
3211 double gui_scaling = g_settings->getFloat("gui_scaling");
3212 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3216 // In fixed-size mode, inventory image size
3217 // is 0.53 inch multiplied by the gui_scaling
3218 // config parameter. This magic size is chosen
3219 // to make the main menu (15.5 inventory images
3220 // wide, including border) just fit into the
3221 // default window (800 pixels wide) at 96 DPI
3222 // and default scaling (1.00).
3223 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3225 // Variables for the maximum imgsize that can fit in the screen.
3226 double fitx_imgsize;
3227 double fity_imgsize;
3229 v2f padded_screensize(
3230 mydata.screensize.X * (1.0f - mydata.padding.X * 2.0f),
3231 mydata.screensize.Y * (1.0f - mydata.padding.Y * 2.0f)
3234 if (mydata.real_coordinates) {
3235 fitx_imgsize = padded_screensize.X / mydata.invsize.X;
3236 fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
3238 // The maximum imgsize in the old coordinate system also needs to
3239 // factor in padding and spacing along with 0.1 inventory slot spare
3240 // and help text space, hence the magic numbers.
3241 fitx_imgsize = padded_screensize.X /
3242 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3243 fity_imgsize = padded_screensize.Y /
3244 ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
3247 s32 min_screen_dim = std::min(padded_screensize.X, padded_screensize.Y);
3249 #ifdef HAVE_TOUCHSCREENGUI
3250 // In Android, the preferred imgsize should be larger to accommodate the
3251 // smaller screensize.
3252 double prefer_imgsize = min_screen_dim / 10 * gui_scaling;
3254 // Desktop computers have more space, so try to fit 15 coordinates.
3255 double prefer_imgsize = min_screen_dim / 15 * gui_scaling;
3257 // Try to use the preferred imgsize, but if that's bigger than the maximum
3258 // size, use the maximum size.
3259 use_imgsize = std::min(prefer_imgsize,
3260 std::min(fitx_imgsize, fity_imgsize));
3263 // Everything else is scaled in proportion to the
3264 // inventory image size. The inventory slot spacing
3265 // is 5/4 image size horizontally and 15/13 image size
3266 // vertically. The padding around the form (incorporating
3267 // the border of the outer inventory slots) is 3/8
3268 // image size. Font height (baseline to baseline)
3269 // is 2/5 vertical inventory slot spacing, and button
3270 // half-height is 7/8 of font height.
3271 imgsize = v2s32(use_imgsize, use_imgsize);
3272 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3273 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3274 m_btn_height = use_imgsize*15.0/13 * 0.35;
3276 m_font = g_fontengine->getFont();
3278 if (mydata.real_coordinates) {
3279 mydata.size = v2s32(
3280 mydata.invsize.X*imgsize.X,
3281 mydata.invsize.Y*imgsize.Y
3284 mydata.size = v2s32(
3285 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3286 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3290 DesiredRect = mydata.rect = core::rect<s32>(
3291 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3292 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3293 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3294 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3297 // Non-size[] form must consist only of text fields and
3298 // implicit "Proceed" button. Use default font, and
3299 // temporary form size which will be recalculated below.
3300 m_font = g_fontengine->getFont();
3301 m_btn_height = font_line_height(m_font) * 0.875;
3302 DesiredRect = core::rect<s32>(
3303 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3304 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3305 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3306 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3309 recalculateAbsolutePosition(false);
3310 mydata.basepos = getBasePos();
3311 m_tooltip_element->setOverrideFont(m_font);
3313 gui::IGUISkin *skin = Environment->getSkin();
3315 gui::IGUIFont *old_font = skin->getFont();
3316 skin->setFont(m_font);
3318 // Add a new element that will hold all the background elements as its children.
3319 // Because it is the first added element, all backgrounds will be behind all
3320 // the other elements.
3321 // (We use an arbitrarily big rect. The actual size is determined later by
3322 // clipping to `this`.)
3323 core::rect<s32> background_parent_rect(0, 0, 100000, 100000);
3324 mydata.background_parent.reset(new gui::IGUIElement(EGUIET_ELEMENT, Environment,
3325 this, -1, background_parent_rect));
3327 pos_offset = v2f32();
3329 // used for formspec versions < 3
3330 std::list<IGUIElement *>::iterator legacy_sort_start = std::prev(Children.end()); // last element
3332 if (enable_prepends) {
3333 // Backup the coordinates so that prepends can use the coordinates of choice.
3334 bool rc_backup = mydata.real_coordinates;
3335 u16 version_backup = m_formspec_version;
3336 mydata.real_coordinates = false; // Old coordinates by default.
3338 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3339 for (const auto &element : prepend_elements)
3340 parseElement(&mydata, element);
3342 // legacy sorting for formspec versions < 3
3343 if (m_formspec_version >= 3)
3344 // prepends do not need to be reordered
3345 legacy_sort_start = std::prev(Children.end()); // last element
3346 else if (version_backup >= 3)
3347 // only prepends elements have to be reordered
3348 legacySortElements(legacy_sort_start);
3350 m_formspec_version = version_backup;
3351 mydata.real_coordinates = rc_backup; // Restore coordinates
3354 for (; i< elements.size(); i++) {
3355 parseElement(&mydata, elements[i]);
3358 if (mydata.current_parent != this) {
3359 errorstream << "Invalid formspec string: scroll_container was never closed!"
3361 } else if (!container_stack.empty()) {
3362 errorstream << "Invalid formspec string: container was never closed!"
3366 // get the scrollbar elements for scroll_containers
3367 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3368 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3369 if (c.first == b.first.fname) {
3370 c.second->setScrollBar(b.second);
3376 // If there are fields without explicit size[], add a "Proceed"
3377 // button and adjust size to fit all the fields.
3378 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3379 mydata.rect = core::rect<s32>(
3380 mydata.screensize.X / 2 - 580 / 2,
3381 mydata.screensize.Y / 2 - 300 / 2,
3382 mydata.screensize.X / 2 + 580 / 2,
3383 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3386 DesiredRect = mydata.rect;
3387 recalculateAbsolutePosition(false);
3388 mydata.basepos = getBasePos();
3391 v2s32 pos = mydata.basepos;
3392 pos.Y = (mydata.simple_field_count + 2) * 60;
3394 v2s32 size = DesiredRect.getSize();
3395 mydata.rect = core::rect<s32>(
3396 size.X / 2 - 70, pos.Y,
3397 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3399 const wchar_t *text = wgettext("Proceed");
3400 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3405 // Set initial focus if parser didn't set it
3406 gui::IGUIElement *focused_element = Environment->getFocus();
3407 if (!focused_element
3408 || !isMyChild(focused_element)
3409 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3412 skin->setFont(old_font);
3415 if (m_formspec_version < 3)
3416 legacySortElements(legacy_sort_start);
3418 // Formname and regeneration setting
3419 if (!m_is_form_regenerated) {
3420 // Only set previous form name if we purposefully showed a new formspec
3421 m_last_formname = m_text_dst->m_formname;
3422 m_is_form_regenerated = true;
3426 void GUIFormSpecMenu::legacySortElements(std::list<IGUIElement *>::iterator from)
3429 Draw order for formspec_version <= 2:
3433 0 All other elements
3435 2 item_image, item_image_button
3440 if (from == Children.end())
3441 from = Children.begin();
3445 std::list<IGUIElement *>::iterator to = Children.end();
3446 // 1: Copy into a sortable container
3447 std::vector<IGUIElement *> elements(from, to);
3449 // 2: Sort the container
3450 std::stable_sort(elements.begin(), elements.end(),
3451 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3452 // TODO: getSpecByID is a linear search. It should made O(1), or cached here.
3453 const FieldSpec *spec_a = getSpecByID(a->getID());
3454 const FieldSpec *spec_b = getSpecByID(b->getID());
3455 return spec_a && spec_b &&
3456 spec_a->priority < spec_b->priority;
3459 // 3: Re-assign the pointers
3460 reorderChildren(from, to, elements);
3464 bool GUIFormSpecMenu::getAndroidUIInput()
3466 if (!hasAndroidUIInput())
3470 if (porting::getInputDialogState() == -1)
3473 std::string fieldname = m_jni_field_name;
3474 m_jni_field_name.clear();
3476 for (const FieldSpec &field : m_fields) {
3477 if (field.fname != fieldname)
3480 IGUIElement *element = getElementFromId(field.fid, true);
3482 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3485 std::string text = porting::getInputDialogValue();
3486 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3492 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3494 for (const GUIInventoryList *e : m_inventorylists) {
3495 s32 item_index = e->getItemIndexAtPos(p);
3496 if (item_index != -1)
3497 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3501 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3504 void GUIFormSpecMenu::drawSelectedItem()
3506 video::IVideoDriver* driver = Environment->getVideoDriver();
3508 if (!m_selected_item) {
3509 // reset rotation time
3510 drawItemStack(driver, m_font, ItemStack(),
3511 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3512 m_client, IT_ROT_DRAGGED);
3516 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3518 InventoryList *list = inv->getList(m_selected_item->listname);
3520 ItemStack stack = list->getItem(m_selected_item->i);
3521 stack.count = m_selected_amount;
3523 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3524 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3525 rect.constrainTo(driver->getViewPort());
3526 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3529 void GUIFormSpecMenu::drawMenu()
3532 const std::string &newform = m_form_src->getForm();
3533 if (newform != m_formspec_string) {
3534 m_formspec_string = newform;
3535 m_is_form_regenerated = false;
3536 regenerateGui(m_screensize_old);
3540 gui::IGUISkin* skin = Environment->getSkin();
3541 sanity_check(skin != NULL);
3542 gui::IGUIFont *old_font = skin->getFont();
3543 skin->setFont(m_font);
3545 m_hovered_item_tooltips.clear();
3547 updateSelectedItem();
3549 video::IVideoDriver* driver = Environment->getVideoDriver();
3552 Draw background color
3554 v2u32 screenSize = driver->getScreenSize();
3555 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3558 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3559 if (m_bgnonfullscreen)
3560 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3563 Draw rect_mode tooltip
3565 m_tooltip_element->setVisible(false);
3567 for (const auto &pair : m_tooltip_rects) {
3568 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3569 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3570 const std::wstring &text = pair.second.tooltip;
3571 if (!text.empty()) {
3572 showTooltip(text, pair.second.color, pair.second.bgcolor);
3578 // Some elements are only visible while being drawn
3579 for (gui::IGUIElement *e : m_clickthrough_elements)
3580 e->setVisible(true);
3583 This is where all the drawing happens.
3585 for (auto child : Children)
3586 if (child->isNotClipped() ||
3587 AbsoluteClippingRect.isRectCollided(
3588 child->getAbsolutePosition()))
3591 for (gui::IGUIElement *e : m_clickthrough_elements)
3592 e->setVisible(false);
3594 // Draw hovered item tooltips
3595 for (const std::string &tooltip : m_hovered_item_tooltips) {
3596 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3597 m_default_tooltip_bgcolor);
3600 if (m_hovered_item_tooltips.empty()) {
3601 // reset rotation time
3602 drawItemStack(driver, m_font, ItemStack(),
3603 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3604 NULL, m_client, IT_ROT_HOVERED);
3607 /* TODO find way to show tooltips on touchscreen */
3608 #ifndef HAVE_TOUCHSCREENGUI
3609 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3613 Draw fields/buttons tooltips and update the mouse cursor
3615 gui::IGUIElement *hovered =
3616 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3618 #ifndef HAVE_TOUCHSCREENGUI
3619 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3621 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3623 bool hovered_element_found = false;
3625 if (hovered != NULL) {
3627 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3628 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3631 s32 id = hovered->getID();
3634 m_old_tooltip_id = id;
3636 if (id == m_old_tooltip_id) {
3637 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3639 m_hovered_time = porting::getTimeMs();
3640 m_old_tooltip_id = id;
3644 // Find and update the current tooltip and cursor icon
3646 for (const FieldSpec &field : m_fields) {
3648 if (field.fid != id)
3651 if (delta >= m_tooltip_show_delay) {
3652 const std::wstring &text = m_tooltips[field.fname].tooltip;
3654 showTooltip(text, m_tooltips[field.fname].color,
3655 m_tooltips[field.fname].bgcolor);
3658 #ifndef HAVE_TOUCHSCREENGUI
3659 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3660 current_cursor_icon != field.fcursor_icon)
3661 cursor_control->setActiveIcon(field.fcursor_icon);
3664 hovered_element_found = true;
3671 if (!hovered_element_found) {
3672 // no element is hovered
3673 #ifndef HAVE_TOUCHSCREENGUI
3674 if (current_cursor_icon != ECI_NORMAL)
3675 cursor_control->setActiveIcon(ECI_NORMAL);
3679 m_tooltip_element->draw();
3682 Draw dragged item stack
3686 skin->setFont(old_font);
3690 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3691 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3693 EnrichedString ntext(text);
3694 ntext.setDefaultColor(color);
3695 if (!ntext.hasBackground())
3696 ntext.setBackground(bgcolor);
3698 setStaticText(m_tooltip_element, ntext);
3700 // Tooltip size and offset
3701 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3702 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3704 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3705 int tooltip_offset_x = m_btn_height;
3706 int tooltip_offset_y = m_btn_height;
3707 #ifdef HAVE_TOUCHSCREENGUI
3708 tooltip_offset_x *= 3;
3709 tooltip_offset_y = 0;
3710 if (m_pointer.X > (s32)screenSize.X / 2)
3711 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3713 // Hide tooltip after ETIE_LEFT_UP
3714 if (m_pointer.X == 0)
3718 // Calculate and set the tooltip position
3719 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3720 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3721 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3722 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3723 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3724 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3726 m_tooltip_element->setRelativePosition(
3728 core::position2d<s32>(tooltip_x, tooltip_y),
3729 core::dimension2d<s32>(tooltip_width, tooltip_height)
3733 // Display the tooltip
3734 m_tooltip_element->setVisible(true);
3735 bringToFront(m_tooltip_element);
3738 void GUIFormSpecMenu::updateSelectedItem()
3740 verifySelectedItem();
3742 // If craftresult is nonempty and nothing else is selected, select it now.
3743 if (!m_selected_item) {
3744 for (const GUIInventoryList *e : m_inventorylists) {
3745 if (e->getListname() != "craftpreview")
3748 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3752 InventoryList *list = inv->getList("craftresult");
3754 if (!list || list->getSize() == 0)
3757 const ItemStack &item = list->getItem(0);
3761 // Grab selected item from the crafting result list
3762 m_selected_item = new GUIInventoryList::ItemSpec;
3763 m_selected_item->inventoryloc = e->getInventoryloc();
3764 m_selected_item->listname = "craftresult";
3765 m_selected_item->i = 0;
3766 m_selected_amount = item.count;
3767 m_selected_dragging = false;
3772 // If craftresult is selected, keep the whole stack selected
3773 if (m_selected_item && m_selected_item->listname == "craftresult")
3774 m_selected_amount = verifySelectedItem().count;
3777 ItemStack GUIFormSpecMenu::verifySelectedItem()
3779 // If the selected stack has become empty for some reason, deselect it.
3780 // If the selected stack has become inaccessible, deselect it.
3781 // If the selected stack has become smaller, adjust m_selected_amount.
3782 // Return the selected stack.
3784 if (m_selected_item) {
3785 if (m_selected_item->isValid()) {
3786 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3788 InventoryList *list = inv->getList(m_selected_item->listname);
3789 if (list && (u32) m_selected_item->i < list->getSize()) {
3790 ItemStack stack = list->getItem(m_selected_item->i);
3791 if (!m_selected_swap.empty()) {
3792 if (m_selected_swap.name == stack.name &&
3793 m_selected_swap.count == stack.count)
3794 m_selected_swap.clear();
3796 m_selected_amount = std::min(m_selected_amount, stack.count);
3805 // selection was not valid
3806 delete m_selected_item;
3807 m_selected_item = nullptr;
3808 m_selected_amount = 0;
3809 m_selected_dragging = false;
3814 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
3820 if (quitmode == quit_mode_accept) {
3821 fields["quit"] = "true";
3824 if (quitmode == quit_mode_cancel) {
3825 fields["quit"] = "true";
3826 m_text_dst->gotText(fields);
3830 if (current_keys_pending.key_down) {
3831 fields["key_down"] = "true";
3832 current_keys_pending.key_down = false;
3835 if (current_keys_pending.key_up) {
3836 fields["key_up"] = "true";
3837 current_keys_pending.key_up = false;
3840 if (current_keys_pending.key_enter) {
3841 fields["key_enter"] = "true";
3842 current_keys_pending.key_enter = false;
3845 if (!current_field_enter_pending.empty()) {
3846 fields["key_enter_field"] = current_field_enter_pending;
3847 current_field_enter_pending = "";
3850 if (current_keys_pending.key_escape) {
3851 fields["key_escape"] = "true";
3852 current_keys_pending.key_escape = false;
3855 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3857 std::string name = s.fname;
3858 if (s.ftype == f_Button) {
3859 fields[name] = wide_to_utf8(s.flabel);
3860 } else if (s.ftype == f_Table) {
3861 GUITable *table = getTable(s.fname);
3863 fields[name] = table->checkEvent();
3865 } else if (s.ftype == f_DropDown) {
3866 // No dynamic cast possible due to some distributions shipped
3867 // without rtti support in Irrlicht
3868 IGUIElement *element = getElementFromId(s.fid, true);
3869 gui::IGUIComboBox *e = NULL;
3870 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3871 e = static_cast<gui::IGUIComboBox *>(element);
3873 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3874 << "field without dropdown element" << std::endl;
3877 s32 selected = e->getSelected();
3878 if (selected >= 0) {
3879 if (m_dropdown_index_event.find(s.fname) !=
3880 m_dropdown_index_event.end()) {
3881 fields[name] = std::to_string(selected + 1);
3883 std::vector<std::string> *dropdown_values =
3884 getDropDownValues(s.fname);
3885 if (dropdown_values && selected < (s32)dropdown_values->size())
3886 fields[name] = (*dropdown_values)[selected];
3889 } else if (s.ftype == f_TabHeader) {
3890 // No dynamic cast possible due to some distributions shipped
3891 // without rtti support in Irrlicht
3892 IGUIElement *element = getElementFromId(s.fid, true);
3893 gui::IGUITabControl *e = nullptr;
3894 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3895 e = static_cast<gui::IGUITabControl *>(element);
3899 fields[name] = itos(e->getActiveTab() + 1);
3901 } else if (s.ftype == f_CheckBox) {
3902 // No dynamic cast possible due to some distributions shipped
3903 // without rtti support in Irrlicht
3904 IGUIElement *element = getElementFromId(s.fid, true);
3905 gui::IGUICheckBox *e = nullptr;
3906 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3907 e = static_cast<gui::IGUICheckBox*>(element);
3912 fields[name] = "true";
3914 fields[name] = "false";
3916 } else if (s.ftype == f_ScrollBar) {
3917 // No dynamic cast possible due to some distributions shipped
3918 // without rtti support in Irrlicht
3919 IGUIElement *element = getElementFromId(s.fid, true);
3920 GUIScrollBar *e = nullptr;
3921 if (element && element->getType() == gui::EGUIET_ELEMENT)
3922 e = static_cast<GUIScrollBar *>(element);
3925 if (s.fdefault == L"Changed")
3926 fields[name] = "CHG:" + itos(e->getPos());
3928 fields[name] = "VAL:" + itos(e->getPos());
3930 } else if (s.ftype == f_AnimatedImage) {
3931 // No dynamic cast possible due to some distributions shipped
3932 // without rtti support in Irrlicht
3933 IGUIElement *element = getElementFromId(s.fid, true);
3934 GUIAnimatedImage *e = nullptr;
3935 if (element && element->getType() == gui::EGUIET_ELEMENT)
3936 e = static_cast<GUIAnimatedImage *>(element);
3939 fields[name] = std::to_string(e->getFrameIndex() + 1);
3941 IGUIElement *e = getElementFromId(s.fid, true);
3943 fields[name] = wide_to_utf8(e->getText());
3948 m_text_dst->gotText(fields);
3952 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3954 // The IGUITabControl renders visually using the skin's selected
3955 // font, which we override for the duration of form drawing,
3956 // but computes tab hotspots based on how it would have rendered
3957 // using the font that is selected at the time of button release.
3958 // To make these two consistent, temporarily override the skin's
3959 // font while the IGUITabControl is processing the event.
3960 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3961 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3962 s32 x = event.MouseInput.X;
3963 s32 y = event.MouseInput.Y;
3964 gui::IGUIElement *hovered =
3965 Environment->getRootGUIElement()->getElementFromPoint(
3966 core::position2d<s32>(x, y));
3967 if (hovered && isMyChild(hovered) &&
3968 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3969 gui::IGUISkin* skin = Environment->getSkin();
3970 sanity_check(skin != NULL);
3971 gui::IGUIFont *old_font = skin->getFont();
3972 skin->setFont(m_font);
3973 bool retval = hovered->OnEvent(event);
3974 skin->setFont(old_font);
3979 // Fix Esc/Return key being eaten by checkboxen and tables
3980 if (event.EventType == EET_KEY_INPUT_EVENT) {
3981 KeyPress kp(event.KeyInput);
3982 if (kp == EscapeKey || kp == CancelKey
3983 || kp == getKeySetting("keymap_inventory")
3984 || event.KeyInput.Key==KEY_RETURN) {
3985 gui::IGUIElement *focused = Environment->getFocus();
3986 if (focused && isMyChild(focused) &&
3987 (focused->getType() == gui::EGUIET_LIST_BOX ||
3988 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3989 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3990 event.KeyInput.Key != KEY_RETURN)) {
3996 // Mouse wheel and move events: send to hovered element instead of focused
3997 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3998 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3999 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4000 event.MouseInput.ButtonStates == 0))) {
4001 s32 x = event.MouseInput.X;
4002 s32 y = event.MouseInput.Y;
4003 gui::IGUIElement *hovered =
4004 Environment->getRootGUIElement()->getElementFromPoint(
4005 core::position2d<s32>(x, y));
4006 if (hovered && isMyChild(hovered)) {
4007 hovered->OnEvent(event);
4008 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
4012 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
4013 /* TODO add a check like:
4014 if (event.JoystickEvent != joystick_we_listen_for)
4017 bool handled = m_joystick->handleEvent(event.JoystickEvent);
4019 if (m_joystick->wasKeyDown(KeyType::ESC)) {
4021 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
4023 acceptInput(quit_mode_accept);
4031 return GUIModalMenu::preprocessEvent(event);
4034 void GUIFormSpecMenu::tryClose()
4038 acceptInput(quit_mode_cancel);
4041 m_text_dst->gotText(L"MenuQuit");
4045 enum ButtonEventType : u8
4058 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
4060 if (event.EventType==EET_KEY_INPUT_EVENT) {
4061 KeyPress kp(event.KeyInput);
4062 if (event.KeyInput.PressedDown && (
4063 (kp == EscapeKey) || (kp == CancelKey) ||
4064 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4069 if (m_client != NULL && event.KeyInput.PressedDown &&
4070 (kp == getKeySetting("keymap_screenshot"))) {
4071 m_client->makeScreenshot();
4074 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4075 m_show_debug = !m_show_debug;
4077 if (event.KeyInput.PressedDown &&
4078 (event.KeyInput.Key==KEY_RETURN ||
4079 event.KeyInput.Key==KEY_UP ||
4080 event.KeyInput.Key==KEY_DOWN)
4082 switch (event.KeyInput.Key) {
4084 current_keys_pending.key_enter = true;
4087 current_keys_pending.key_up = true;
4090 current_keys_pending.key_down = true;
4094 //can't happen at all!
4095 FATAL_ERROR("Reached a source line that can't ever been reached");
4098 if (current_keys_pending.key_enter && m_allowclose) {
4099 acceptInput(quit_mode_accept);
4109 /* Mouse event other than movement, or crossing the border of inventory
4110 field while holding right mouse button
4112 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4113 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4114 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4115 event.MouseInput.isRightPressed() &&
4116 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4118 // Get selected item and hovered/clicked item (s)
4120 m_old_tooltip_id = -1;
4121 updateSelectedItem();
4122 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4124 Inventory *inv_selected = NULL;
4125 Inventory *inv_s = NULL;
4126 InventoryList *list_s = NULL;
4128 if (m_selected_item) {
4129 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4130 sanity_check(inv_selected);
4131 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4138 inv_s = m_invmgr->getInventory(s.inventoryloc);
4141 errorstream << "InventoryMenu: The selected inventory location "
4142 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4144 s.i = -1; // make it invalid again
4148 list_s = inv_s->getList(s.listname);
4149 if (list_s == NULL) {
4150 verbosestream << "InventoryMenu: The selected inventory list \""
4151 << s.listname << "\" does not exist" << std::endl;
4152 s.i = -1; // make it invalid again
4156 if ((u32)s.i >= list_s->getSize()) {
4157 infostream << "InventoryMenu: The selected inventory list \""
4158 << s.listname << "\" is too small (i=" << s.i << ", size="
4159 << list_s->getSize() << ")" << std::endl;
4160 s.i = -1; // make it invalid again
4164 s_count = list_s->getItem(s.i).count;
4167 bool identical = m_selected_item && s.isValid() &&
4168 (inv_selected == inv_s) &&
4169 (m_selected_item->listname == s.listname) &&
4170 (m_selected_item->i == s.i);
4172 ButtonEventType button = BET_LEFT;
4173 ButtonEventType updown = BET_OTHER;
4174 switch (event.MouseInput.Event) {
4175 case EMIE_LMOUSE_PRESSED_DOWN:
4176 button = BET_LEFT; updown = BET_DOWN;
4178 case EMIE_RMOUSE_PRESSED_DOWN:
4179 button = BET_RIGHT; updown = BET_DOWN;
4181 case EMIE_MMOUSE_PRESSED_DOWN:
4182 button = BET_MIDDLE; updown = BET_DOWN;
4184 case EMIE_MOUSE_WHEEL:
4185 button = (event.MouseInput.Wheel > 0) ?
4186 BET_WHEEL_UP : BET_WHEEL_DOWN;
4189 case EMIE_LMOUSE_LEFT_UP:
4190 button = BET_LEFT; updown = BET_UP;
4192 case EMIE_RMOUSE_LEFT_UP:
4193 button = BET_RIGHT; updown = BET_UP;
4195 case EMIE_MMOUSE_LEFT_UP:
4196 button = BET_MIDDLE; updown = BET_UP;
4198 case EMIE_MOUSE_MOVED:
4205 // Set this number to a positive value to generate a move action
4206 // from m_selected_item to s.
4207 u32 move_amount = 0;
4209 // Set this number to a positive value to generate a move action
4210 // from s to the next inventory ring.
4211 u32 shift_move_amount = 0;
4213 // Set this number to a positive value to generate a drop action
4214 // from m_selected_item.
4215 u32 drop_amount = 0;
4217 // Set this number to a positive value to generate a craft action at s.
4218 u32 craft_amount = 0;
4222 // Some mouse button has been pressed
4224 //infostream << "Mouse button " << button << " pressed at p=("
4225 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4228 m_selected_dragging = false;
4230 if (s.isValid() && s.listname == "craftpreview") {
4231 // Craft preview has been clicked: craft
4232 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4233 } else if (!m_selected_item) {
4234 if (s_count && button != BET_WHEEL_UP) {
4235 // Non-empty stack has been clicked: select or shift-move it
4236 m_selected_item = new GUIInventoryList::ItemSpec(s);
4239 if (button == BET_RIGHT)
4240 count = (s_count + 1) / 2;
4241 else if (button == BET_MIDDLE)
4242 count = MYMIN(s_count, 10);
4243 else if (button == BET_WHEEL_DOWN)
4248 if (!event.MouseInput.Shift) {
4249 // no shift: select item
4250 m_selected_amount = count;
4251 m_selected_dragging = button != BET_WHEEL_DOWN;
4252 m_auto_place = false;
4254 // shift pressed: move item, right click moves 1
4255 shift_move_amount = button == BET_RIGHT ? 1 : count;
4258 } else { // m_selected_item != NULL
4259 assert(m_selected_amount >= 1);
4262 // Clicked a slot: move
4263 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4265 else if (button == BET_MIDDLE)
4266 move_amount = MYMIN(m_selected_amount, 10);
4267 else if (button == BET_LEFT)
4268 move_amount = m_selected_amount;
4272 if (button == BET_WHEEL_DOWN) {
4273 if (m_selected_amount < s_count)
4274 ++m_selected_amount;
4276 if (move_amount >= m_selected_amount)
4277 m_selected_amount = 0;
4279 m_selected_amount -= move_amount;
4283 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4284 && button != BET_WHEEL_DOWN) {
4285 // Clicked outside of the window: drop
4286 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4288 else if (button == BET_MIDDLE)
4289 drop_amount = MYMIN(m_selected_amount, 10);
4291 drop_amount = m_selected_amount;
4296 // Some mouse button has been released
4298 //infostream<<"Mouse button "<<button<<" released at p=("
4299 // <<p.X<<","<<p.Y<<")"<<std::endl;
4301 if (m_selected_dragging && m_selected_item) {
4304 // Dragged to different slot: move all selected
4305 move_amount = m_selected_amount;
4307 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4308 // Dragged outside of window: drop all selected
4309 drop_amount = m_selected_amount;
4313 m_selected_dragging = false;
4314 // Keep track of whether the mouse button be released
4315 // One click is drag without dropping. Click + release
4316 // + click changes to drop item when moved mode
4317 if (m_selected_item)
4318 m_auto_place = true;
4321 // Mouse has been moved and rmb is down and mouse pointer just
4322 // entered a new inventory field (checked in the entry-if, this
4323 // is the only action here that is generated by mouse movement)
4324 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4326 // TODO: middle mouse to move 10 items might be handy
4328 // Only move an item if the destination slot is empty
4329 // or contains the same item type as what is going to be
4331 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4332 InventoryList *list_to = list_s;
4333 assert(list_from && list_to);
4334 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4335 ItemStack stack_to = list_to->getItem(s.i);
4336 if (stack_to.empty() || stack_to.name == stack_from.name)
4345 // Possibly send inventory action to server
4346 if (move_amount > 0) {
4347 // Send IAction::Move
4349 assert(m_selected_item && m_selected_item->isValid());
4350 assert(s.isValid());
4352 assert(inv_selected && inv_s);
4353 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4354 InventoryList *list_to = list_s;
4355 assert(list_from && list_to);
4356 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4357 ItemStack stack_to = list_to->getItem(s.i);
4359 // Check how many items can be moved
4360 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4361 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4363 // If source stack cannot be added to destination stack at all,
4365 if (leftover.count == stack_from.count &&
4366 leftover.name == stack_from.name) {
4368 if (m_selected_swap.empty()) {
4369 m_selected_amount = stack_to.count;
4370 m_selected_dragging = false;
4372 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4373 // Skip next validation checks due async inventory calls
4374 m_selected_swap = stack_to;
4379 // Source stack goes fully into destination stack
4380 else if (leftover.empty()) {
4381 m_selected_amount -= move_amount;
4383 // Source stack goes partly into destination stack
4385 move_amount -= leftover.count;
4386 m_selected_amount -= move_amount;
4390 infostream << "Handing IAction::Move to manager" << std::endl;
4391 IMoveAction *a = new IMoveAction();
4392 a->count = move_amount;
4393 a->from_inv = m_selected_item->inventoryloc;
4394 a->from_list = m_selected_item->listname;
4395 a->from_i = m_selected_item->i;
4396 a->to_inv = s.inventoryloc;
4397 a->to_list = s.listname;
4399 m_invmgr->inventoryAction(a);
4401 } else if (shift_move_amount > 0) {
4402 u32 mis = m_inventory_rings.size();
4404 for (; i < mis; i++) {
4405 const ListRingSpec &sp = m_inventory_rings[i];
4406 if (sp.inventoryloc == s.inventoryloc
4407 && sp.listname == s.listname)
4411 if (i >= mis) // if not found
4413 u32 to_inv_ind = (i + 1) % mis;
4414 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4415 InventoryList *list_from = list_s;
4418 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4421 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4424 ItemStack stack_from = list_from->getItem(s.i);
4425 assert(shift_move_amount <= stack_from.count);
4427 infostream << "Handing IAction::Move to manager" << std::endl;
4428 IMoveAction *a = new IMoveAction();
4429 a->count = shift_move_amount;
4430 a->from_inv = s.inventoryloc;
4431 a->from_list = s.listname;
4433 a->to_inv = to_inv_sp.inventoryloc;
4434 a->to_list = to_inv_sp.listname;
4435 a->move_somewhere = true;
4436 m_invmgr->inventoryAction(a);
4438 } else if (drop_amount > 0) {
4439 // Send IAction::Drop
4441 assert(m_selected_item && m_selected_item->isValid());
4442 assert(inv_selected);
4443 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4445 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4447 // Check how many items can be dropped
4448 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4449 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4450 m_selected_amount -= drop_amount;
4452 infostream << "Handing IAction::Drop to manager" << std::endl;
4453 IDropAction *a = new IDropAction();
4454 a->count = drop_amount;
4455 a->from_inv = m_selected_item->inventoryloc;
4456 a->from_list = m_selected_item->listname;
4457 a->from_i = m_selected_item->i;
4458 m_invmgr->inventoryAction(a);
4459 } else if (craft_amount > 0) {
4460 assert(s.isValid());
4462 // if there are no items selected or the selected item
4463 // belongs to craftresult list, proceed with crafting
4464 if (!m_selected_item ||
4465 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4469 // Send IACTION_CRAFT
4470 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4471 ICraftAction *a = new ICraftAction();
4472 a->count = craft_amount;
4473 a->craft_inv = s.inventoryloc;
4474 m_invmgr->inventoryAction(a);
4478 // If m_selected_amount has been decreased to zero, deselect
4479 if (m_selected_amount == 0) {
4480 m_selected_swap.clear();
4481 delete m_selected_item;
4482 m_selected_item = nullptr;
4483 m_selected_amount = 0;
4484 m_selected_dragging = false;
4486 m_old_pointer = m_pointer;
4489 if (event.EventType == EET_GUI_EVENT) {
4490 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4492 // find the element that was clicked
4493 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4494 if ((s.ftype == f_TabHeader) &&
4495 (s.fid == event.GUIEvent.Caller->getID())) {
4496 if (!s.sound.empty() && m_sound_manager)
4497 m_sound_manager->playSound(s.sound, false, 1.0f);
4505 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4507 if (!canTakeFocus(event.GUIEvent.Element)) {
4508 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4510 // Returning true disables focus change
4514 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4515 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4516 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4517 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4518 s32 caller_id = event.GUIEvent.Caller->getID();
4520 if (caller_id == 257) {
4522 acceptInput(quit_mode_accept);
4526 m_text_dst->gotText(L"ExitButton");
4528 // quitMenu deallocates menu
4532 // find the element that was clicked
4533 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4534 // if its a button, set the send field so
4535 // lua knows which button was pressed
4537 if (caller_id != s.fid)
4540 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4541 if (!s.sound.empty() && m_sound_manager)
4542 m_sound_manager->playSound(s.sound, false, 1.0f);
4547 acceptInput(quit_mode_accept);
4550 m_text_dst->gotText(L"ExitButton");
4555 acceptInput(quit_mode_no);
4559 } else if (s.ftype == f_DropDown) {
4560 // only send the changed dropdown
4561 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4562 if (s2.ftype == f_DropDown) {
4566 if (!s.sound.empty() && m_sound_manager)
4567 m_sound_manager->playSound(s.sound, false, 1.0f);
4569 acceptInput(quit_mode_no);
4571 // revert configuration to make sure dropdowns are sent on
4572 // regular button click
4573 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4574 if (s2.ftype == f_DropDown) {
4579 } else if (s.ftype == f_ScrollBar) {
4580 s.fdefault = L"Changed";
4581 acceptInput(quit_mode_no);
4583 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4584 if (!s.sound.empty() && m_sound_manager)
4585 m_sound_manager->playSound(s.sound, false, 1.0f);
4593 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4594 // move scroll_containers
4595 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4596 c.second->onScrollEvent(event.GUIEvent.Caller);
4599 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4600 if (event.GUIEvent.Caller->getID() > 257) {
4601 bool close_on_enter = true;
4602 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4603 if (s.ftype == f_Unknown &&
4604 s.fid == event.GUIEvent.Caller->getID()) {
4605 current_field_enter_pending = s.fname;
4606 std::unordered_map<std::string, bool>::const_iterator it =
4607 field_close_on_enter.find(s.fname);
4608 if (it != field_close_on_enter.end())
4609 close_on_enter = (*it).second;
4615 if (m_allowclose && close_on_enter) {
4616 current_keys_pending.key_enter = true;
4617 acceptInput(quit_mode_accept);
4620 current_keys_pending.key_enter = true;
4623 // quitMenu deallocates menu
4628 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4629 int current_id = event.GUIEvent.Caller->getID();
4630 if (current_id > 257) {
4631 // find the element that was clicked
4632 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4633 // if it's a table, set the send field
4634 // so lua knows which table was changed
4635 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4646 return Parent ? Parent->OnEvent(event) : false;
4650 * get name of element by element id
4651 * @param id of element
4652 * @return name string or empty string
4654 std::string GUIFormSpecMenu::getNameByID(s32 id)
4656 for (FieldSpec &spec : m_fields) {
4664 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4666 for (FieldSpec &spec : m_fields) {
4674 * get label of element by id
4675 * @param id of element
4676 * @return label string or empty string
4678 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4680 for (FieldSpec &spec : m_fields) {
4687 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4688 const std::string &name, const std::string &parent_type) {
4689 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4692 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4693 const std::string &type, const std::string &name, const std::string &parent_type)
4695 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4697 auto it = theme_by_type.find("*");
4698 if (it != theme_by_type.end()) {
4699 for (const StyleSpec &spec : it->second)
4700 ret[(u32)spec.getState()] |= spec;
4703 it = theme_by_name.find("*");
4704 if (it != theme_by_name.end()) {
4705 for (const StyleSpec &spec : it->second)
4706 ret[(u32)spec.getState()] |= spec;
4709 if (!parent_type.empty()) {
4710 it = theme_by_type.find(parent_type);
4711 if (it != theme_by_type.end()) {
4712 for (const StyleSpec &spec : it->second)
4713 ret[(u32)spec.getState()] |= spec;
4717 it = theme_by_type.find(type);
4718 if (it != theme_by_type.end()) {
4719 for (const StyleSpec &spec : it->second)
4720 ret[(u32)spec.getState()] |= spec;
4723 it = theme_by_name.find(name);
4724 if (it != theme_by_name.end()) {
4725 for (const StyleSpec &spec : it->second)
4726 ret[(u32)spec.getState()] |= spec;