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, 4, parts))
773 size_t offset = parts.size() >= 3;
775 std::vector<std::string> v_pos = split(parts[0],',');
776 MY_CHECKPOS("image", 0);
778 std::vector<std::string> v_geom;
779 if (parts.size() >= 3) {
780 v_geom = split(parts[1],',');
781 MY_CHECKGEOM("image", 1);
784 std::string name = unescape_string(parts[1 + offset]);
785 video::ITexture *texture = m_tsrc->getTexture(name);
790 if (parts.size() < 3) {
791 if (texture != nullptr) {
792 core::dimension2du dim = texture->getOriginalSize();
800 if (data->real_coordinates) {
801 pos = getRealCoordinateBasePos(v_pos);
802 if (parts.size() >= 3)
803 geom = getRealCoordinateGeometry(v_geom);
805 pos = getElementBasePos(&v_pos);
806 if (parts.size() >= 3) {
807 geom.X = stof(v_geom[0]) * (float)imgsize.X;
808 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
812 if (!data->explicit_size)
813 warningstream << "Invalid use of image without a size[] element" << std::endl;
819 258 + m_fields.size(),
823 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
825 core::rect<s32> middle;
826 if (parts.size() >= 4)
827 parseMiddleRect(parts[3], &middle);
829 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent,
832 e->setTexture(texture);
833 e->setMiddleRect(middle);
835 auto style = getDefaultStyleForElement("image", spec.fname);
836 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
838 // Animated images should let events through
839 m_clickthrough_elements.push_back(e);
841 m_fields.push_back(spec);
844 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
846 std::vector<std::string> parts;
847 if (!precheckElement("animated_image", element, 6, 8, parts))
850 std::vector<std::string> v_pos = split(parts[0], ',');
851 std::vector<std::string> v_geom = split(parts[1], ',');
852 std::string name = parts[2];
853 std::string texture_name = unescape_string(parts[3]);
854 s32 frame_count = stoi(parts[4]);
855 s32 frame_duration = stoi(parts[5]);
857 MY_CHECKPOS("animated_image", 0);
858 MY_CHECKGEOM("animated_image", 1);
863 if (data->real_coordinates) {
864 pos = getRealCoordinateBasePos(v_pos);
865 geom = getRealCoordinateGeometry(v_geom);
867 pos = getElementBasePos(&v_pos);
868 geom.X = stof(v_geom[0]) * (float)imgsize.X;
869 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
872 if (!data->explicit_size)
873 warningstream << "Invalid use of animated_image without a size[] element"
880 258 + m_fields.size()
882 spec.ftype = f_AnimatedImage;
885 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
887 core::rect<s32> middle;
888 if (parts.size() >= 8)
889 parseMiddleRect(parts[7], &middle);
891 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent,
894 e->setTexture(m_tsrc->getTexture(texture_name));
895 e->setMiddleRect(middle);
896 e->setFrameDuration(frame_duration);
897 e->setFrameCount(frame_count);
898 if (parts.size() >= 7)
899 e->setFrameIndex(stoi(parts[6]) - 1);
901 auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
902 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
904 // Animated images should let events through
905 m_clickthrough_elements.push_back(e);
907 m_fields.push_back(spec);
910 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
912 std::vector<std::string> parts;
913 if (!precheckElement("item_image", element, 3, 3, parts))
916 std::vector<std::string> v_pos = split(parts[0],',');
917 std::vector<std::string> v_geom = split(parts[1],',');
918 std::string name = parts[2];
920 MY_CHECKPOS("item_image",0);
921 MY_CHECKGEOM("item_image",1);
926 if (data->real_coordinates) {
927 pos = getRealCoordinateBasePos(v_pos);
928 geom = getRealCoordinateGeometry(v_geom);
930 pos = getElementBasePos(&v_pos);
931 geom.X = stof(v_geom[0]) * (float)imgsize.X;
932 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
935 if(!data->explicit_size)
936 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
942 258 + m_fields.size(),
945 spec.ftype = f_ItemImage;
947 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
948 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
949 auto style = getDefaultStyleForElement("item_image", spec.fname);
950 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
952 // item images should let events through
953 m_clickthrough_elements.push_back(e);
955 m_fields.push_back(spec);
958 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
959 const std::string &type)
961 std::vector<std::string> parts;
962 if (!precheckElement("button", element, 4, 4, parts))
965 std::vector<std::string> v_pos = split(parts[0],',');
966 std::vector<std::string> v_geom = split(parts[1],',');
967 std::string name = parts[2];
968 std::string label = parts[3];
970 MY_CHECKPOS("button",0);
971 MY_CHECKGEOM("button",1);
975 core::rect<s32> rect;
977 if (data->real_coordinates) {
978 pos = getRealCoordinateBasePos(v_pos);
979 geom = getRealCoordinateGeometry(v_geom);
980 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
983 pos = getElementBasePos(&v_pos);
984 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
985 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
987 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
988 pos.X + geom.X, pos.Y + m_btn_height);
991 if(!data->explicit_size)
992 warningstream<<"invalid use of button without a size[] element"<<std::endl;
994 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1000 258 + m_fields.size()
1002 spec.ftype = f_Button;
1003 if(type == "button_exit")
1004 spec.is_exit = true;
1006 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1007 data->current_parent, spec.fid, spec.flabel.c_str());
1009 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1011 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1013 e->setStyles(style);
1015 if (spec.fname == m_focused_element) {
1016 Environment->setFocus(e);
1019 m_fields.push_back(spec);
1022 bool GUIFormSpecMenu::parseMiddleRect(const std::string &value, core::rect<s32> *parsed_rect)
1024 core::rect<s32> rect;
1025 std::vector<std::string> v_rect = split(value, ',');
1027 if (v_rect.size() == 1) {
1028 s32 x = stoi(v_rect[0]);
1029 rect.UpperLeftCorner = core::vector2di(x, x);
1030 rect.LowerRightCorner = core::vector2di(-x, -x);
1031 } else if (v_rect.size() == 2) {
1032 s32 x = stoi(v_rect[0]);
1033 s32 y = stoi(v_rect[1]);
1034 rect.UpperLeftCorner = core::vector2di(x, y);
1035 rect.LowerRightCorner = core::vector2di(-x, -y);
1036 // `-x` is interpreted as `w - x`
1037 } else if (v_rect.size() == 4) {
1038 rect.UpperLeftCorner = core::vector2di(stoi(v_rect[0]), stoi(v_rect[1]));
1039 rect.LowerRightCorner = core::vector2di(stoi(v_rect[2]), stoi(v_rect[3]));
1041 warningstream << "Invalid rectangle string format: \"" << value
1042 << "\"" << std::endl;
1046 *parsed_rect = rect;
1051 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1053 std::vector<std::string> parts;
1054 if (!precheckElement("background", element, 3, 5, parts))
1057 std::vector<std::string> v_pos = split(parts[0],',');
1058 std::vector<std::string> v_geom = split(parts[1],',');
1059 std::string name = unescape_string(parts[2]);
1061 MY_CHECKPOS("background",0);
1062 MY_CHECKGEOM("background",1);
1067 if (data->real_coordinates) {
1068 pos = getRealCoordinateBasePos(v_pos);
1069 geom = getRealCoordinateGeometry(v_geom);
1071 pos = getElementBasePos(&v_pos);
1072 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1073 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1075 geom.X = stof(v_geom[0]) * spacing.X;
1076 geom.Y = stof(v_geom[1]) * spacing.Y;
1080 if (parts.size() >= 4 && is_yes(parts[3])) {
1081 if (data->real_coordinates) {
1082 pos = getRealCoordinateBasePos(v_pos) * -1;
1085 pos.X = stoi(v_pos[0]); //acts as offset
1086 pos.Y = stoi(v_pos[1]);
1091 core::rect<s32> middle;
1092 if (parts.size() >= 5)
1093 parseMiddleRect(parts[4], &middle);
1095 if (!data->explicit_size && !clip)
1096 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1102 258 + m_fields.size()
1105 core::rect<s32> rect;
1107 // no auto_clip => position like normal image
1108 rect = core::rect<s32>(pos, pos + geom);
1110 // it will be auto-clipped when drawing
1111 rect = core::rect<s32>(-pos, pos);
1114 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, data->background_parent.get(),
1115 spec.fid, rect, name, middle, m_tsrc, clip);
1117 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1119 e->setNotClipped(true);
1121 m_fields.push_back(spec);
1125 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1127 std::vector<std::string> parts = split(element,';');
1129 data->table_options.clear();
1130 for (const std::string &part : parts) {
1131 // Parse table option
1132 std::string opt = unescape_string(part);
1133 data->table_options.push_back(GUITable::splitOption(opt));
1137 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1139 std::vector<std::string> parts = split(element,';');
1141 data->table_columns.clear();
1142 for (const std::string &part : parts) {
1143 std::vector<std::string> col_parts = split(part,',');
1144 GUITable::TableColumn column;
1145 // Parse column type
1146 if (!col_parts.empty())
1147 column.type = col_parts[0];
1148 // Parse column options
1149 for (size_t j = 1; j < col_parts.size(); ++j) {
1150 std::string opt = unescape_string(col_parts[j]);
1151 column.options.push_back(GUITable::splitOption(opt));
1153 data->table_columns.push_back(column);
1157 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1159 std::vector<std::string> parts;
1160 if (!precheckElement("table", element, 4, 5, parts))
1163 std::vector<std::string> v_pos = split(parts[0],',');
1164 std::vector<std::string> v_geom = split(parts[1],',');
1165 std::string name = parts[2];
1166 std::vector<std::string> items = split(parts[3],',');
1167 std::string str_initial_selection;
1168 std::string str_transparent = "false";
1170 if (parts.size() >= 5)
1171 str_initial_selection = parts[4];
1173 MY_CHECKPOS("table",0);
1174 MY_CHECKGEOM("table",1);
1179 if (data->real_coordinates) {
1180 pos = getRealCoordinateBasePos(v_pos);
1181 geom = getRealCoordinateGeometry(v_geom);
1183 pos = getElementBasePos(&v_pos);
1184 geom.X = stof(v_geom[0]) * spacing.X;
1185 geom.Y = stof(v_geom[1]) * spacing.Y;
1188 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1194 258 + m_fields.size()
1197 spec.ftype = f_Table;
1199 for (std::string &item : items) {
1200 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1203 //now really show table
1204 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1207 if (spec.fname == m_focused_element) {
1208 Environment->setFocus(e);
1211 e->setTable(data->table_options, data->table_columns, items);
1213 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1214 e->setDynamicData(data->table_dyndata[name]);
1217 if (!str_initial_selection.empty() && str_initial_selection != "0")
1218 e->setSelected(stoi(str_initial_selection));
1220 auto style = getDefaultStyleForElement("table", name);
1221 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1222 e->setOverrideFont(style.getFont());
1224 m_tables.emplace_back(spec, e);
1225 m_fields.push_back(spec);
1228 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1230 std::vector<std::string> parts;
1231 if (!precheckElement("textlist", element, 4, 6, parts))
1234 std::vector<std::string> v_pos = split(parts[0],',');
1235 std::vector<std::string> v_geom = split(parts[1],',');
1236 std::string name = parts[2];
1237 std::vector<std::string> items = split(parts[3],',');
1238 std::string str_initial_selection;
1239 std::string str_transparent = "false";
1241 if (parts.size() >= 5)
1242 str_initial_selection = parts[4];
1244 if (parts.size() >= 6)
1245 str_transparent = parts[5];
1247 MY_CHECKPOS("textlist",0);
1248 MY_CHECKGEOM("textlist",1);
1253 if (data->real_coordinates) {
1254 pos = getRealCoordinateBasePos(v_pos);
1255 geom = getRealCoordinateGeometry(v_geom);
1257 pos = getElementBasePos(&v_pos);
1258 geom.X = stof(v_geom[0]) * spacing.X;
1259 geom.Y = stof(v_geom[1]) * spacing.Y;
1262 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1268 258 + m_fields.size()
1271 spec.ftype = f_Table;
1273 for (std::string &item : items) {
1274 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1277 //now really show list
1278 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1281 if (spec.fname == m_focused_element) {
1282 Environment->setFocus(e);
1285 e->setTextList(items, is_yes(str_transparent));
1287 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1288 e->setDynamicData(data->table_dyndata[name]);
1291 if (!str_initial_selection.empty() && str_initial_selection != "0")
1292 e->setSelected(stoi(str_initial_selection));
1294 auto style = getDefaultStyleForElement("textlist", name);
1295 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1296 e->setOverrideFont(style.getFont());
1298 m_tables.emplace_back(spec, e);
1299 m_fields.push_back(spec);
1302 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1304 std::vector<std::string> parts;
1305 if (!precheckElement("dropdown", element, 5, 6, parts))
1308 std::vector<std::string> v_pos = split(parts[0], ',');
1309 std::string name = parts[2];
1310 std::vector<std::string> items = split(parts[3], ',');
1311 std::string str_initial_selection = parts[4];
1313 if (parts.size() >= 6 && is_yes(parts[5]))
1314 m_dropdown_index_event[name] = true;
1316 MY_CHECKPOS("dropdown",0);
1320 core::rect<s32> rect;
1322 if (data->real_coordinates) {
1323 std::vector<std::string> v_geom = split(parts[1],',');
1325 if (v_geom.size() == 1)
1326 v_geom.emplace_back("1");
1328 MY_CHECKGEOM("dropdown",1);
1330 pos = getRealCoordinateBasePos(v_pos);
1331 geom = getRealCoordinateGeometry(v_geom);
1332 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1334 pos = getElementBasePos(&v_pos);
1336 s32 width = stof(parts[1]) * spacing.Y;
1338 rect = core::rect<s32>(pos.X, pos.Y,
1339 pos.X + width, pos.Y + (m_btn_height * 2));
1346 258 + m_fields.size()
1349 spec.ftype = f_DropDown;
1352 //now really show list
1353 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1356 if (spec.fname == m_focused_element) {
1357 Environment->setFocus(e);
1360 for (const std::string &item : items) {
1361 e->addItem(unescape_translate(unescape_string(
1362 utf8_to_wide(item))).c_str());
1365 if (!str_initial_selection.empty())
1366 e->setSelected(stoi(str_initial_selection)-1);
1368 auto style = getDefaultStyleForElement("dropdown", name);
1370 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1372 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1374 m_fields.push_back(spec);
1376 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1377 std::vector<std::string> &values = m_dropdowns.back().second;
1378 for (const std::string &item : items) {
1379 values.push_back(unescape_string(item));
1383 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1385 std::vector<std::string> parts;
1386 if (!precheckElement("field_close_on_enter", element, 2, 2, parts))
1389 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1392 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1394 std::vector<std::string> parts;
1395 if (!precheckElement("pwdfield", element, 4, 4, parts))
1398 std::vector<std::string> v_pos = split(parts[0],',');
1399 std::vector<std::string> v_geom = split(parts[1],',');
1400 std::string name = parts[2];
1401 std::string label = parts[3];
1403 MY_CHECKPOS("pwdfield",0);
1404 MY_CHECKGEOM("pwdfield",1);
1409 if (data->real_coordinates) {
1410 pos = getRealCoordinateBasePos(v_pos);
1411 geom = getRealCoordinateGeometry(v_geom);
1413 pos = getElementBasePos(&v_pos);
1416 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1418 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1419 pos.Y -= m_btn_height;
1420 geom.Y = m_btn_height*2;
1423 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1425 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1431 258 + m_fields.size(),
1437 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1438 data->current_parent, spec.fid);
1440 if (spec.fname == m_focused_element) {
1441 Environment->setFocus(e);
1444 if (label.length() >= 1) {
1445 int font_height = g_fontengine->getTextHeight();
1446 rect.UpperLeftCorner.Y -= font_height;
1447 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1448 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1449 data->current_parent, 0);
1452 e->setPasswordBox(true,L'*');
1454 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1455 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1456 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1457 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1458 e->setOverrideFont(style.getFont());
1461 evt.EventType = EET_KEY_INPUT_EVENT;
1462 evt.KeyInput.Key = KEY_END;
1463 evt.KeyInput.Char = 0;
1464 evt.KeyInput.Control = false;
1465 evt.KeyInput.Shift = false;
1466 evt.KeyInput.PressedDown = true;
1469 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1470 // warning referring to field_close_on_enter[]!
1472 m_fields.push_back(spec);
1475 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1476 core::rect<s32> &rect, bool is_multiline)
1478 bool is_editable = !spec.fname.empty();
1479 if (!is_editable && !is_multiline) {
1480 // spec field id to 0, this stops submit searching for a value that isn't there
1481 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1482 data->current_parent, 0);
1488 } else if (is_multiline &&
1489 spec.fdefault.empty() && !spec.flabel.empty()) {
1490 // Multiline textareas: swap default and label for backwards compat
1491 spec.flabel.swap(spec.fdefault);
1494 gui::IGUIEditBox *e = nullptr;
1496 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1497 data->current_parent, spec.fid, rect, is_editable, true);
1498 } else if (is_editable) {
1499 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1500 data->current_parent, spec.fid);
1504 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1507 if (is_editable && spec.fname == m_focused_element)
1508 Environment->setFocus(e);
1511 e->setMultiLine(true);
1512 e->setWordWrap(true);
1513 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1516 evt.EventType = EET_KEY_INPUT_EVENT;
1517 evt.KeyInput.Key = KEY_END;
1518 evt.KeyInput.Char = 0;
1519 evt.KeyInput.Control = 0;
1520 evt.KeyInput.Shift = 0;
1521 evt.KeyInput.PressedDown = true;
1525 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1526 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1527 bool border = style.getBool(StyleSpec::BORDER, true);
1528 e->setDrawBorder(border);
1529 e->setDrawBackground(border);
1530 e->setOverrideFont(style.getFont());
1535 if (!spec.flabel.empty()) {
1536 int font_height = g_fontengine->getTextHeight();
1537 rect.UpperLeftCorner.Y -= font_height;
1538 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1539 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1540 rect, false, true, data->current_parent, 0);
1543 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1547 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1548 std::vector<std::string> &parts)
1550 std::string name = parts[0];
1551 std::string label = parts[1];
1552 std::string default_val = parts[2];
1554 core::rect<s32> rect;
1556 if (data->explicit_size)
1557 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1559 v2s32 pos = getElementBasePos(nullptr);
1560 pos.Y = (data->simple_field_count + 2) * 60;
1561 v2s32 size = DesiredRect.getSize();
1563 rect = core::rect<s32>(
1564 size.X / 2 - 150, pos.Y,
1565 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1570 default_val = m_form_src->resolveText(default_val);
1573 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1578 utf8_to_wide(unescape_string(default_val)),
1579 258 + m_fields.size(),
1584 createTextField(data, spec, rect, false);
1586 m_fields.push_back(spec);
1588 data->simple_field_count++;
1591 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1592 const std::string &type)
1594 std::vector<std::string> v_pos = split(parts[0],',');
1595 std::vector<std::string> v_geom = split(parts[1],',');
1596 std::string name = parts[2];
1597 std::string label = parts[3];
1598 std::string default_val = parts[4];
1600 MY_CHECKPOS(type,0);
1601 MY_CHECKGEOM(type,1);
1606 if (data->real_coordinates) {
1607 pos = getRealCoordinateBasePos(v_pos);
1608 geom = getRealCoordinateGeometry(v_geom);
1610 pos = getElementBasePos(&v_pos);
1613 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1615 if (type == "textarea")
1617 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1618 pos.Y += m_btn_height;
1622 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1623 pos.Y -= m_btn_height;
1624 geom.Y = m_btn_height*2;
1628 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1630 if(!data->explicit_size)
1631 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1634 default_val = m_form_src->resolveText(default_val);
1637 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1642 utf8_to_wide(unescape_string(default_val)),
1643 258 + m_fields.size(),
1648 createTextField(data, spec, rect, type == "textarea");
1650 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1651 // warning referring to field_close_on_enter[]!
1653 m_fields.push_back(spec);
1656 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1657 const std::string &type)
1659 std::vector<std::string> parts;
1660 if (!precheckElement(type, element, 3, 5, parts))
1663 if (parts.size() == 3 || parts.size() == 4) {
1664 parseSimpleField(data, parts);
1668 // Else: >= 5 arguments in "parts"
1669 parseTextArea(data, parts, type);
1672 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1674 MY_CHECKCLIENT("list");
1676 std::vector<std::string> parts;
1677 if (!precheckElement("hypertext", element, 4, 4, parts))
1680 std::vector<std::string> v_pos = split(parts[0], ',');
1681 std::vector<std::string> v_geom = split(parts[1], ',');
1682 std::string name = parts[2];
1683 std::string text = parts[3];
1685 MY_CHECKPOS("hypertext", 0);
1686 MY_CHECKGEOM("hypertext", 1);
1691 if (data->real_coordinates) {
1692 pos = getRealCoordinateBasePos(v_pos);
1693 geom = getRealCoordinateGeometry(v_geom);
1695 pos = getElementBasePos(&v_pos);
1698 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1699 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1700 pos.Y += m_btn_height;
1703 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1706 text = m_form_src->resolveText(text);
1710 translate_string(utf8_to_wide(unescape_string(text))),
1712 258 + m_fields.size()
1715 spec.ftype = f_HyperText;
1717 auto style = getDefaultStyleForElement("hypertext", spec.fname);
1718 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1720 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1721 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1724 m_fields.push_back(spec);
1727 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1729 std::vector<std::string> parts;
1730 if (!precheckElement("label", element, 2, 2, parts))
1733 std::vector<std::string> v_pos = split(parts[0],',');
1735 MY_CHECKPOS("label",0);
1737 if(!data->explicit_size)
1738 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1740 auto style = getDefaultStyleForElement("label", "");
1741 gui::IGUIFont *font = style.getFont();
1745 EnrichedString str(unescape_string(utf8_to_wide(parts[1])));
1748 for (size_t i = 0; str_pos < str.size(); ++i) {
1750 size_t str_nl = str.getString().find(L'\n', str_pos);
1751 if (str_nl == std::wstring::npos)
1752 str_nl = str.getString().size();
1753 EnrichedString line = str.substr(str_pos, str_nl - str_pos);
1754 str_pos += line.size() + 1;
1756 core::rect<s32> rect;
1758 if (data->real_coordinates) {
1759 // Lines are spaced at the distance of 1/2 imgsize.
1760 // This alows lines that line up with the new elements
1761 // easily without sacrificing good line distance. If
1762 // it was one whole imgsize, it would have too much
1764 v2s32 pos = getRealCoordinateBasePos(v_pos);
1766 // Labels are positioned by their center, not their top.
1767 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1769 rect = core::rect<s32>(
1771 pos.X + font->getDimension(line.c_str()).Width,
1775 // Lines are spaced at the nominal distance of
1776 // 2/5 inventory slot, even if the font doesn't
1777 // quite match that. This provides consistent
1778 // form layout, at the expense of sometimes
1779 // having sub-optimal spacing for the font.
1780 // We multiply by 2 and then divide by 5, rather
1781 // than multiply by 0.4, to get exact results
1782 // in the integer cases: 0.4 is not exactly
1783 // representable in binary floating point.
1785 v2s32 pos = getElementBasePos(nullptr);
1786 pos.X += stof(v_pos[0]) * spacing.X;
1787 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1789 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1791 rect = core::rect<s32>(
1792 pos.X, pos.Y - m_btn_height,
1793 pos.X + font->getDimension(line.c_str()).Width,
1794 pos.Y + m_btn_height);
1801 258 + m_fields.size(),
1804 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1805 line, rect, false, false, data->current_parent,
1807 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1809 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1810 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1811 e->setOverrideFont(font);
1813 m_fields.push_back(spec);
1815 // labels should let events through
1817 m_clickthrough_elements.push_back(e);
1821 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1823 std::vector<std::string> parts;
1824 if (!precheckElement("vertlabel", element, 2, 2, parts))
1827 std::vector<std::string> v_pos = split(parts[0],',');
1828 std::wstring text = unescape_translate(
1829 unescape_string(utf8_to_wide(parts[1])));
1831 MY_CHECKPOS("vertlabel",1);
1833 auto style = getDefaultStyleForElement("vertlabel", "", "label");
1834 gui::IGUIFont *font = style.getFont();
1839 core::rect<s32> rect;
1841 if (data->real_coordinates) {
1842 pos = getRealCoordinateBasePos(v_pos);
1844 // Vertlabels are positioned by center, not left.
1845 pos.X -= imgsize.X / 2;
1847 // We use text.length + 1 because without it, the rect
1848 // isn't quite tall enough and cuts off the text.
1849 rect = core::rect<s32>(pos.X, pos.Y,
1851 pos.Y + font_line_height(font) *
1852 (text.length() + 1));
1855 pos = getElementBasePos(&v_pos);
1857 // As above, the length must be one longer. The width of
1858 // the rect (15 pixels) seems rather arbitrary, but
1859 // changing it might break something.
1860 rect = core::rect<s32>(
1861 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1863 font_line_height(font) *
1864 (text.length() + 1) +
1865 ((imgsize.Y/2) - m_btn_height));
1868 if(!data->explicit_size)
1869 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1873 for (wchar_t i : text) {
1882 258 + m_fields.size()
1884 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1885 rect, false, false, data->current_parent, spec.fid);
1886 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1888 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1889 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1890 e->setOverrideFont(font);
1892 m_fields.push_back(spec);
1894 // vertlabels should let events through
1896 m_clickthrough_elements.push_back(e);
1899 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1900 const std::string &type)
1902 std::vector<std::string> parts;
1903 if (!precheckElement("image_button", element, 5, 8, parts))
1906 if (parts.size() == 6) {
1907 // Invalid argument count.
1908 errorstream << "Invalid image_button element(" << parts.size() << "): '" << element << "'" << std::endl;
1912 std::vector<std::string> v_pos = split(parts[0],',');
1913 std::vector<std::string> v_geom = split(parts[1],',');
1914 std::string image_name = parts[2];
1915 std::string name = parts[3];
1916 std::string label = parts[4];
1918 MY_CHECKPOS("image_button",0);
1919 MY_CHECKGEOM("image_button",1);
1921 std::string pressed_image_name;
1923 if (parts.size() >= 8) {
1924 pressed_image_name = parts[7];
1930 if (data->real_coordinates) {
1931 pos = getRealCoordinateBasePos(v_pos);
1932 geom = getRealCoordinateGeometry(v_geom);
1934 pos = getElementBasePos(&v_pos);
1935 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1936 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1939 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1942 if (!data->explicit_size)
1943 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1945 image_name = unescape_string(image_name);
1946 pressed_image_name = unescape_string(pressed_image_name);
1948 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1953 utf8_to_wide(image_name),
1954 258 + m_fields.size()
1956 spec.ftype = f_Button;
1957 if (type == "image_button_exit")
1958 spec.is_exit = true;
1960 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1961 data->current_parent, spec.fid, spec.flabel.c_str());
1963 if (spec.fname == m_focused_element) {
1964 Environment->setFocus(e);
1967 auto style = getStyleForElement("image_button", spec.fname);
1969 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1971 // Override style properties with values specified directly in the element
1972 if (!image_name.empty())
1973 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1975 if (!pressed_image_name.empty())
1976 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
1978 if (parts.size() >= 7) {
1979 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
1980 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
1983 e->setStyles(style);
1984 e->setScaleImage(true);
1986 m_fields.push_back(spec);
1989 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1991 std::vector<std::string> parts;
1992 if (!precheckElement("tabheader", element, 4, 7, parts))
1995 // Length 7: Additional "height" parameter after "pos". Only valid with real_coordinates.
1996 // Note: New arguments for the "height" syntax cannot be added without breaking older clients.
1997 if (parts.size() == 5 || (parts.size() == 7 && !data->real_coordinates)) {
1998 errorstream << "Invalid tabheader element(" << parts.size() << "): '"
1999 << element << "'" << std::endl;
2003 std::vector<std::string> v_pos = split(parts[0],',');
2005 // If we're using real coordinates, add an extra field for height.
2006 // Width is not here because tabs are the width of the text, and
2007 // there's no reason to change that.
2009 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2010 bool auto_width = true;
2011 if (parts.size() == 7) {
2014 v_geom = split(parts[1], ',');
2015 if (v_geom.size() == 1)
2016 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2021 std::string name = parts[i+1];
2022 std::vector<std::string> buttons = split(parts[i+2], ',');
2023 std::string str_index = parts[i+3];
2024 bool show_background = true;
2025 bool show_border = true;
2026 int tab_index = stoi(str_index) - 1;
2028 MY_CHECKPOS("tabheader", 0);
2030 if (parts.size() == 6 + i) {
2031 if (parts[4+i] == "true")
2032 show_background = false;
2033 if (parts[5+i] == "false")
2034 show_border = false;
2041 258 + m_fields.size()
2044 spec.ftype = f_TabHeader;
2049 if (data->real_coordinates) {
2050 pos = getRealCoordinateBasePos(v_pos);
2052 geom = getRealCoordinateGeometry(v_geom);
2053 // Set default height
2054 if (parts.size() <= 6)
2055 geom.Y = m_btn_height * 2;
2056 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2058 geom.X = DesiredRect.getWidth(); // Set automatic width
2060 MY_CHECKGEOM("tabheader", 1);
2062 v2f32 pos_f = pos_offset * spacing;
2063 pos_f.X += stof(v_pos[0]) * spacing.X;
2064 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2065 pos = v2s32(pos_f.X, pos_f.Y);
2067 geom.Y = m_btn_height * 2;
2068 geom.X = DesiredRect.getWidth();
2071 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2074 gui::IGUITabControl *e = Environment->addTabControl(rect,
2075 data->current_parent, show_background, show_border, spec.fid);
2076 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2077 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2078 e->setTabHeight(geom.Y);
2080 auto style = getDefaultStyleForElement("tabheader", name);
2082 spec.sound = style.get(StyleSpec::Property::SOUND, "");
2084 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2086 for (const std::string &button : buttons) {
2087 auto tab = e->addTab(unescape_translate(unescape_string(
2088 utf8_to_wide(button))).c_str(), -1);
2089 if (style.isNotDefault(StyleSpec::BGCOLOR))
2090 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2092 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2095 if ((tab_index >= 0) &&
2096 (buttons.size() < INT_MAX) &&
2097 (tab_index < (int) buttons.size()))
2098 e->setActiveTab(tab_index);
2100 m_fields.push_back(spec);
2103 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2105 MY_CHECKCLIENT("item_image_button");
2107 std::vector<std::string> parts;
2108 if (!precheckElement("item_image_button", element, 5, 5, parts))
2111 std::vector<std::string> v_pos = split(parts[0],',');
2112 std::vector<std::string> v_geom = split(parts[1],',');
2113 std::string item_name = parts[2];
2114 std::string name = parts[3];
2115 std::string label = parts[4];
2117 label = unescape_string(label);
2118 item_name = unescape_string(item_name);
2120 MY_CHECKPOS("item_image_button",0);
2121 MY_CHECKGEOM("item_image_button",1);
2126 if (data->real_coordinates) {
2127 pos = getRealCoordinateBasePos(v_pos);
2128 geom = getRealCoordinateGeometry(v_geom);
2130 pos = getElementBasePos(&v_pos);
2131 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2132 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2135 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2137 if(!data->explicit_size)
2138 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2140 IItemDefManager *idef = m_client->idef();
2142 item.deSerialize(item_name, idef);
2145 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2146 m_default_tooltip_bgcolor,
2147 m_default_tooltip_color);
2149 // the spec for the button
2152 utf8_to_wide(label),
2153 utf8_to_wide(item_name),
2154 258 + m_fields.size(),
2158 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2159 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2160 item_name, m_client);
2162 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2164 spec_btn.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
2166 e_btn->setStyles(style);
2168 if (spec_btn.fname == m_focused_element) {
2169 Environment->setFocus(e_btn);
2172 spec_btn.ftype = f_Button;
2173 rect += data->basepos-padding;
2174 spec_btn.rect = rect;
2175 m_fields.push_back(spec_btn);
2178 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2180 std::vector<std::string> parts;
2181 if (!precheckElement("box", element, 3, 3, parts))
2184 std::vector<std::string> v_pos = split(parts[0], ',');
2185 std::vector<std::string> v_geom = split(parts[1], ',');
2187 MY_CHECKPOS("box", 0);
2188 MY_CHECKGEOM("box", 1);
2193 if (data->real_coordinates) {
2194 pos = getRealCoordinateBasePos(v_pos);
2195 geom = getRealCoordinateGeometry(v_geom);
2197 pos = getElementBasePos(&v_pos);
2198 geom.X = stof(v_geom[0]) * spacing.X;
2199 geom.Y = stof(v_geom[1]) * spacing.Y;
2206 258 + m_fields.size(),
2211 auto style = getDefaultStyleForElement("box", spec.fname);
2213 video::SColor tmp_color;
2214 std::array<video::SColor, 4> colors;
2215 std::array<video::SColor, 4> bordercolors = {0x0, 0x0, 0x0, 0x0};
2216 std::array<s32, 4> borderwidths = {0, 0, 0, 0};
2218 if (parseColorString(parts[2], tmp_color, true, 0x8C)) {
2219 colors = {tmp_color, tmp_color, tmp_color, tmp_color};
2221 colors = style.getColorArray(StyleSpec::COLORS, {0x0, 0x0, 0x0, 0x0});
2222 bordercolors = style.getColorArray(StyleSpec::BORDERCOLORS,
2223 {0x0, 0x0, 0x0, 0x0});
2224 borderwidths = style.getIntArray(StyleSpec::BORDERWIDTHS, {0, 0, 0, 0});
2227 core::rect<s32> rect(pos, pos + geom);
2229 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid, rect,
2230 colors, bordercolors, borderwidths);
2231 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2234 m_fields.push_back(spec);
2237 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2239 std::vector<std::string> parts;
2240 if (!precheckElement("bgcolor", element, 1, 3, parts))
2243 const u32 parameter_count = parts.size();
2245 if (parameter_count > 2 && m_formspec_version < 3) {
2246 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2247 << element << "'" << std::endl;
2252 if (parameter_count >= 1 && parts[0] != "")
2253 parseColorString(parts[0], m_bgcolor, false);
2256 if (parameter_count >= 2) {
2257 if (parts[1] == "both") {
2258 m_bgnonfullscreen = true;
2259 m_bgfullscreen = true;
2260 } else if (parts[1] == "neither") {
2261 m_bgnonfullscreen = false;
2262 m_bgfullscreen = false;
2263 } else if (parts[1] != "" || m_formspec_version < 3) {
2264 m_bgfullscreen = is_yes(parts[1]);
2265 m_bgnonfullscreen = !m_bgfullscreen;
2270 if (parameter_count >= 3 && parts[2] != "")
2271 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2274 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2276 std::vector<std::string> parts;
2277 // Legacy Note: If clients older than 5.5.0-dev are supplied with additional arguments,
2278 // the tooltip colors will be ignored.
2279 if (!precheckElement("listcolors", element, 2, 5, parts))
2282 if (parts.size() == 4) {
2283 // Invalid argument combination
2284 errorstream << "Invalid listcolors element(" << parts.size() << "): '"
2285 << element << "'" << std::endl;
2289 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2290 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2292 if (parts.size() >= 3) {
2293 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2295 data->inventorylist_options.slotborder = true;
2298 if (parts.size() >= 5) {
2299 video::SColor tmp_color;
2301 if (parseColorString(parts[3], tmp_color, false))
2302 m_default_tooltip_bgcolor = tmp_color;
2303 if (parseColorString(parts[4], tmp_color, false))
2304 m_default_tooltip_color = tmp_color;
2307 // update all already parsed inventorylists
2308 for (GUIInventoryList *e : m_inventorylists) {
2309 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2310 data->inventorylist_options.slotbg_h);
2311 e->setSlotBorders(data->inventorylist_options.slotborder,
2312 data->inventorylist_options.slotbordercolor);
2316 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2318 std::vector<std::string> parts;
2319 if (!precheckElement("tooltip", element, 2, 5, parts))
2322 // Get mode and check size
2323 bool rect_mode = parts[0].find(',') != std::string::npos;
2324 size_t base_size = rect_mode ? 3 : 2;
2325 if (parts.size() != base_size && parts.size() != base_size + 2) {
2326 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2327 << element << "'" << std::endl;
2332 video::SColor bgcolor = m_default_tooltip_bgcolor;
2333 video::SColor color = m_default_tooltip_color;
2334 if (parts.size() == base_size + 2 &&
2335 (!parseColorString(parts[base_size], bgcolor, false) ||
2336 !parseColorString(parts[base_size + 1], color, false))) {
2337 errorstream << "Invalid color in tooltip element(" << parts.size()
2338 << "): '" << element << "'" << std::endl;
2342 // Make tooltip spec
2343 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2344 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2348 std::vector<std::string> v_pos = split(parts[0], ',');
2349 std::vector<std::string> v_geom = split(parts[1], ',');
2351 MY_CHECKPOS("tooltip", 0);
2352 MY_CHECKGEOM("tooltip", 1);
2357 if (data->real_coordinates) {
2358 pos = getRealCoordinateBasePos(v_pos);
2359 geom = getRealCoordinateGeometry(v_geom);
2361 pos = getElementBasePos(&v_pos);
2362 geom.X = stof(v_geom[0]) * spacing.X;
2363 geom.Y = stof(v_geom[1]) * spacing.Y;
2366 FieldSpec fieldspec(
2370 258 + m_fields.size()
2373 core::rect<s32> rect(pos, pos + geom);
2375 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2376 data->current_parent, fieldspec.fid, rect);
2378 // the element the rect tooltip is bound to should not block mouse-clicks
2379 e->setVisible(false);
2381 m_fields.push_back(fieldspec);
2382 m_tooltip_rects.emplace_back(e, spec);
2385 m_tooltips[parts[0]] = spec;
2389 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2395 std::vector<std::string> parts = split(data,'[');
2397 if (parts.size() < 2) {
2401 if (trim(parts[0]) != "formspec_version") {
2405 if (is_number(parts[1])) {
2406 m_formspec_version = mystoi(parts[1]);
2413 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2415 if (element.empty())
2418 std::vector<std::string> parts = split(element,'[');
2420 if (parts.size() < 2)
2423 std::string type = trim(parts[0]);
2424 std::string description = trim(parts[1]);
2426 if (type != "size" && type != "invsize")
2429 if (type == "invsize")
2430 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2432 parseSize(data, description);
2437 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2439 if (element.empty())
2442 std::vector<std::string> parts = split(element, '[');
2444 if (parts.size() != 2)
2447 std::string type = trim(parts[0]);
2448 std::string description = trim(parts[1]);
2450 if (type != "position")
2453 parsePosition(data, description);
2458 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2460 std::vector<std::string> parts = split(element, ';');
2462 if (parts.size() == 1 ||
2463 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2464 std::vector<std::string> v_geom = split(parts[0], ',');
2466 MY_CHECKGEOM("position", 0);
2468 data->offset.X = stof(v_geom[0]);
2469 data->offset.Y = stof(v_geom[1]);
2473 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2476 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2478 if (element.empty())
2481 std::vector<std::string> parts = split(element, '[');
2483 if (parts.size() != 2)
2486 std::string type = trim(parts[0]);
2487 std::string description = trim(parts[1]);
2489 if (type != "anchor")
2492 parseAnchor(data, description);
2497 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2499 std::vector<std::string> parts = split(element, ';');
2501 if (parts.size() == 1 ||
2502 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2503 std::vector<std::string> v_geom = split(parts[0], ',');
2505 MY_CHECKGEOM("anchor", 0);
2507 data->anchor.X = stof(v_geom[0]);
2508 data->anchor.Y = stof(v_geom[1]);
2512 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2513 << "'" << std::endl;
2516 bool GUIFormSpecMenu::parsePaddingDirect(parserData *data, const std::string &element)
2518 if (element.empty())
2521 std::vector<std::string> parts = split(element, '[');
2523 if (parts.size() != 2)
2526 std::string type = trim(parts[0]);
2527 std::string description = trim(parts[1]);
2529 if (type != "padding")
2532 parsePadding(data, description);
2537 void GUIFormSpecMenu::parsePadding(parserData *data, const std::string &element)
2539 std::vector<std::string> parts = split(element, ';');
2541 if (parts.size() == 1 ||
2542 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2543 std::vector<std::string> v_geom = split(parts[0], ',');
2545 MY_CHECKGEOM("padding", 0);
2547 data->padding.X = stof(v_geom[0]);
2548 data->padding.Y = stof(v_geom[1]);
2552 errorstream << "Invalid padding element (" << parts.size() << "): '" << element
2553 << "'" << std::endl;
2556 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2558 std::vector<std::string> parts = split(element, ';');
2560 if (parts.size() < 2) {
2561 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2562 << "'" << std::endl;
2569 for (size_t i = 1; i < parts.size(); i++) {
2570 size_t equal_pos = parts[i].find('=');
2571 if (equal_pos == std::string::npos) {
2572 errorstream << "Invalid style element (Property missing value): '" << element
2573 << "'" << std::endl;
2577 std::string propname = trim(parts[i].substr(0, equal_pos));
2578 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2580 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2582 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2583 if (prop == StyleSpec::NONE) {
2584 if (property_warned.find(propname) != property_warned.end()) {
2585 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2587 << "'" << std::endl;
2588 property_warned.insert(propname);
2593 spec.set(prop, value);
2596 std::vector<std::string> selectors = split(parts[0], ',');
2597 for (size_t sel = 0; sel < selectors.size(); sel++) {
2598 std::string selector = trim(selectors[sel]);
2600 // Copy the style properties to a new StyleSpec
2601 // This allows a separate state mask per-selector
2602 StyleSpec selector_spec = spec;
2604 // Parse state information, if it exists
2605 bool state_valid = true;
2606 size_t state_pos = selector.find(':');
2607 if (state_pos != std::string::npos) {
2608 std::string state_str = selector.substr(state_pos + 1);
2609 selector = selector.substr(0, state_pos);
2611 if (state_str.empty()) {
2612 errorstream << "Invalid style element (Invalid state): '" << element
2613 << "'" << std::endl;
2614 state_valid = false;
2616 std::vector<std::string> states = split(state_str, '+');
2617 for (std::string &state : states) {
2618 StyleSpec::State converted = StyleSpec::getStateByName(state);
2619 if (converted == StyleSpec::STATE_INVALID) {
2620 infostream << "Unknown style state " << state <<
2621 " in element '" << element << "'" << std::endl;
2622 state_valid = false;
2626 selector_spec.addState(converted);
2632 // Skip this selector
2637 theme_by_type[selector].push_back(selector_spec);
2639 theme_by_name[selector].push_back(selector_spec);
2642 // Backwards-compatibility for existing _hovered/_pressed properties
2643 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2644 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2645 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2646 StyleSpec hover_spec;
2647 hover_spec.addState(StyleSpec::STATE_HOVERED);
2649 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2650 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2652 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2653 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2655 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2656 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2660 theme_by_type[selector].push_back(hover_spec);
2662 theme_by_name[selector].push_back(hover_spec);
2665 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2666 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2667 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2668 StyleSpec press_spec;
2669 press_spec.addState(StyleSpec::STATE_PRESSED);
2671 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2672 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2674 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2675 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2677 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2678 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2682 theme_by_type[selector].push_back(press_spec);
2684 theme_by_name[selector].push_back(press_spec);
2692 void GUIFormSpecMenu::parseSetFocus(const std::string &element)
2694 std::vector<std::string> parts;
2695 if (!precheckElement("set_focus", element, 1, 2, parts))
2698 if (m_is_form_regenerated)
2699 return; // Never focus on resizing
2701 bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
2702 if (force_focus || m_text_dst->m_formname != m_last_formname)
2706 void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element)
2708 MY_CHECKCLIENT("model");
2710 std::vector<std::string> parts;
2711 if (!precheckElement("model", element, 5, 10, parts))
2714 // Avoid length checks by resizing
2715 if (parts.size() < 10)
2718 std::vector<std::string> v_pos = split(parts[0], ',');
2719 std::vector<std::string> v_geom = split(parts[1], ',');
2720 std::string name = unescape_string(parts[2]);
2721 std::string meshstr = unescape_string(parts[3]);
2722 std::vector<std::string> textures = split(parts[4], ',');
2723 std::vector<std::string> vec_rot = split(parts[5], ',');
2724 bool inf_rotation = is_yes(parts[6]);
2725 bool mousectrl = is_yes(parts[7]) || parts[7].empty(); // default true
2726 std::vector<std::string> frame_loop = split(parts[8], ',');
2727 std::string speed = unescape_string(parts[9]);
2729 MY_CHECKPOS("model", 0);
2730 MY_CHECKGEOM("model", 1);
2735 if (data->real_coordinates) {
2736 pos = getRealCoordinateBasePos(v_pos);
2737 geom = getRealCoordinateGeometry(v_geom);
2739 pos = getElementBasePos(&v_pos);
2740 geom.X = stof(v_geom[0]) * (float)imgsize.X;
2741 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
2744 if (!data->explicit_size)
2745 warningstream << "invalid use of model without a size[] element" << std::endl;
2747 scene::IAnimatedMesh *mesh = m_client->getMesh(meshstr);
2750 errorstream << "Invalid model element: Unable to load mesh:"
2751 << std::endl << "\t" << meshstr << std::endl;
2759 258 + m_fields.size()
2762 core::rect<s32> rect(pos, pos + geom);
2764 GUIScene *e = new GUIScene(Environment, m_client->getSceneManager(),
2765 data->current_parent, rect, spec.fid);
2767 auto meshnode = e->setMesh(mesh);
2769 for (u32 i = 0; i < textures.size() && i < meshnode->getMaterialCount(); ++i)
2770 e->setTexture(i, m_tsrc->getTexture(unescape_string(textures[i])));
2772 if (vec_rot.size() >= 2)
2773 e->setRotation(v2f(stof(vec_rot[0]), stof(vec_rot[1])));
2775 e->enableContinuousRotation(inf_rotation);
2776 e->enableMouseControl(mousectrl);
2778 s32 frame_loop_begin = 0;
2779 s32 frame_loop_end = 0x7FFFFFFF;
2781 if (frame_loop.size() == 2) {
2782 frame_loop_begin = stoi(frame_loop[0]);
2783 frame_loop_end = stoi(frame_loop[1]);
2786 e->setFrameLoop(frame_loop_begin, frame_loop_end);
2787 e->setAnimationSpeed(stof(speed));
2789 auto style = getStyleForElement("model", spec.fname);
2790 e->setStyles(style);
2793 m_fields.push_back(spec);
2796 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2799 if (element.empty())
2802 if (parseVersionDirect(element))
2805 size_t pos = element.find('[');
2806 if (pos == std::string::npos)
2809 std::string type = trim(element.substr(0, pos));
2810 std::string description = element.substr(pos+1);
2812 if (type == "container") {
2813 parseContainer(data, description);
2817 if (type == "container_end") {
2818 parseContainerEnd(data);
2822 if (type == "list") {
2823 parseList(data, description);
2827 if (type == "listring") {
2828 parseListRing(data, description);
2832 if (type == "checkbox") {
2833 parseCheckbox(data, description);
2837 if (type == "image") {
2838 parseImage(data, description);
2842 if (type == "animated_image") {
2843 parseAnimatedImage(data, description);
2847 if (type == "item_image") {
2848 parseItemImage(data, description);
2852 if (type == "button" || type == "button_exit") {
2853 parseButton(data, description, type);
2857 if (type == "background" || type == "background9") {
2858 parseBackground(data, description);
2862 if (type == "tableoptions"){
2863 parseTableOptions(data,description);
2867 if (type == "tablecolumns"){
2868 parseTableColumns(data,description);
2872 if (type == "table"){
2873 parseTable(data,description);
2877 if (type == "textlist"){
2878 parseTextList(data,description);
2882 if (type == "dropdown"){
2883 parseDropDown(data,description);
2887 if (type == "field_close_on_enter") {
2888 parseFieldCloseOnEnter(data, description);
2892 if (type == "pwdfield") {
2893 parsePwdField(data,description);
2897 if ((type == "field") || (type == "textarea")){
2898 parseField(data,description,type);
2902 if (type == "hypertext") {
2903 parseHyperText(data,description);
2907 if (type == "label") {
2908 parseLabel(data,description);
2912 if (type == "vertlabel") {
2913 parseVertLabel(data,description);
2917 if (type == "item_image_button") {
2918 parseItemImageButton(data,description);
2922 if ((type == "image_button") || (type == "image_button_exit")) {
2923 parseImageButton(data,description,type);
2927 if (type == "tabheader") {
2928 parseTabHeader(data,description);
2932 if (type == "box") {
2933 parseBox(data,description);
2937 if (type == "bgcolor") {
2938 parseBackgroundColor(data,description);
2942 if (type == "listcolors") {
2943 parseListColors(data,description);
2947 if (type == "tooltip") {
2948 parseTooltip(data,description);
2952 if (type == "scrollbar") {
2953 parseScrollBar(data, description);
2957 if (type == "real_coordinates") {
2958 data->real_coordinates = is_yes(description);
2962 if (type == "style") {
2963 parseStyle(data, description, false);
2967 if (type == "style_type") {
2968 parseStyle(data, description, true);
2972 if (type == "scrollbaroptions") {
2973 parseScrollBarOptions(data, description);
2977 if (type == "scroll_container") {
2978 parseScrollContainer(data, description);
2982 if (type == "scroll_container_end") {
2983 parseScrollContainerEnd(data);
2987 if (type == "set_focus") {
2988 parseSetFocus(description);
2992 if (type == "model") {
2993 parseModel(data, description);
2998 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
3002 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
3004 // Useless to regenerate without a screensize
3005 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
3011 // Preserve stuff only on same form, not on a new form.
3012 if (m_text_dst->m_formname == m_last_formname) {
3013 // Preserve tables/textlists
3014 for (auto &m_table : m_tables) {
3015 std::string tablename = m_table.first.fname;
3016 GUITable *table = m_table.second;
3017 mydata.table_dyndata[tablename] = table->getDynamicData();
3021 gui::IGUIElement *focused_element = Environment->getFocus();
3022 if (focused_element && focused_element->getParent() == this) {
3023 s32 focused_id = focused_element->getID();
3024 if (focused_id > 257) {
3025 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
3026 if (field.fid == focused_id) {
3027 m_focused_element = field.fname;
3034 // Don't keep old focus value
3035 m_focused_element = "";
3039 removeAllChildren();
3042 for (auto &table_it : m_tables)
3043 table_it.second->drop();
3044 for (auto &inventorylist_it : m_inventorylists)
3045 inventorylist_it->drop();
3046 for (auto &checkbox_it : m_checkboxes)
3047 checkbox_it.second->drop();
3048 for (auto &scrollbar_it : m_scrollbars)
3049 scrollbar_it.second->drop();
3050 for (auto &tooltip_rect_it : m_tooltip_rects)
3051 tooltip_rect_it.first->drop();
3052 for (auto &clickthrough_it : m_clickthrough_elements)
3053 clickthrough_it->drop();
3054 for (auto &scroll_container_it : m_scroll_containers)
3055 scroll_container_it.second->drop();
3057 mydata.size = v2s32(100, 100);
3058 mydata.screensize = screensize;
3059 mydata.offset = v2f32(0.5f, 0.5f);
3060 mydata.anchor = v2f32(0.5f, 0.5f);
3061 mydata.padding = v2f32(0.05f, 0.05f);
3062 mydata.simple_field_count = 0;
3064 // Base position of contents of form
3065 mydata.basepos = getBasePos();
3067 // the parent for the parsed elements
3068 mydata.current_parent = this;
3070 m_inventorylists.clear();
3072 m_checkboxes.clear();
3073 m_scrollbars.clear();
3076 m_tooltip_rects.clear();
3077 m_inventory_rings.clear();
3078 m_dropdowns.clear();
3079 m_scroll_containers.clear();
3080 theme_by_name.clear();
3081 theme_by_type.clear();
3082 m_clickthrough_elements.clear();
3083 field_close_on_enter.clear();
3084 m_dropdown_index_event.clear();
3086 m_bgnonfullscreen = true;
3087 m_bgfullscreen = false;
3089 m_formspec_version = 1;
3092 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
3093 m_bgcolor = video::SColor(
3094 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
3095 clamp_u8(myround(formspec_bgcolor.X)),
3096 clamp_u8(myround(formspec_bgcolor.Y)),
3097 clamp_u8(myround(formspec_bgcolor.Z))
3102 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
3103 m_fullscreen_bgcolor = video::SColor(
3104 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
3105 clamp_u8(myround(formspec_bgcolor.X)),
3106 clamp_u8(myround(formspec_bgcolor.Y)),
3107 clamp_u8(myround(formspec_bgcolor.Z))
3111 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3112 m_default_tooltip_color = video::SColor(255,255,255,255);
3116 assert(!m_tooltip_element);
3117 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3118 m_tooltip_element = gui::StaticText::add(Environment, L"",
3119 core::rect<s32>(0, 0, 110, 18));
3120 m_tooltip_element->enableOverrideColor(true);
3121 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3122 m_tooltip_element->setDrawBackground(true);
3123 m_tooltip_element->setDrawBorder(true);
3124 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3125 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3126 m_tooltip_element->setWordWrap(false);
3127 //we're not parent so no autograb for this one!
3128 m_tooltip_element->grab();
3131 std::vector<std::string> elements = split(m_formspec_string,']');
3134 /* try to read version from first element only */
3135 if (!elements.empty()) {
3136 if (parseVersionDirect(elements[0])) {
3141 /* we need size first in order to calculate image scale */
3142 mydata.explicit_size = false;
3143 for (; i< elements.size(); i++) {
3144 if (!parseSizeDirect(&mydata, elements[i])) {
3149 /* "position" element is always after "size" element if it used */
3150 for (; i< elements.size(); i++) {
3151 if (!parsePositionDirect(&mydata, elements[i])) {
3156 /* "anchor" element is always after "position" (or "size" element) if it used */
3157 for (; i< elements.size(); i++) {
3158 if (!parseAnchorDirect(&mydata, elements[i])) {
3163 /* "padding" element is always after "anchor" and previous if it is used */
3164 for (; i < elements.size(); i++) {
3165 if (!parsePaddingDirect(&mydata, elements[i])) {
3170 /* "no_prepend" element is always after "padding" and previous if it used */
3171 bool enable_prepends = true;
3172 for (; i < elements.size(); i++) {
3173 if (elements[i].empty())
3176 std::vector<std::string> parts = split(elements[i], '[');
3177 if (trim(parts[0]) == "no_prepend")
3178 enable_prepends = false;
3183 /* Copy of the "real_coordinates" element for after the form size. */
3184 mydata.real_coordinates = m_formspec_version >= 2;
3185 for (; i < elements.size(); i++) {
3186 std::vector<std::string> parts = split(elements[i], '[');
3187 std::string name = trim(parts[0]);
3188 if (name != "real_coordinates" || parts.size() != 2)
3189 break; // Invalid format
3191 mydata.real_coordinates = is_yes(trim(parts[1]));
3194 if (mydata.explicit_size) {
3195 // compute scaling for specified form size
3197 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3198 v2u32 delta = current_screensize - m_lockscreensize;
3200 if (current_screensize.Y > m_lockscreensize.Y)
3205 if (current_screensize.X > m_lockscreensize.X)
3210 offset = v2s32(delta.X,delta.Y);
3212 mydata.screensize = m_lockscreensize;
3214 offset = v2s32(0,0);
3217 const double gui_scaling = g_settings->getFloat("gui_scaling", 0.5f, 42.0f);
3218 const double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3222 // In fixed-size mode, inventory image size
3223 // is 0.53 inch multiplied by the gui_scaling
3224 // config parameter. This magic size is chosen
3225 // to make the main menu (15.5 inventory images
3226 // wide, including border) just fit into the
3227 // default window (800 pixels wide) at 96 DPI
3228 // and default scaling (1.00).
3229 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3231 // Variables for the maximum imgsize that can fit in the screen.
3232 double fitx_imgsize;
3233 double fity_imgsize;
3235 v2f padded_screensize(
3236 mydata.screensize.X * (1.0f - mydata.padding.X * 2.0f),
3237 mydata.screensize.Y * (1.0f - mydata.padding.Y * 2.0f)
3240 if (mydata.real_coordinates) {
3241 fitx_imgsize = padded_screensize.X / mydata.invsize.X;
3242 fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
3244 // The maximum imgsize in the old coordinate system also needs to
3245 // factor in padding and spacing along with 0.1 inventory slot spare
3246 // and help text space, hence the magic numbers.
3247 fitx_imgsize = padded_screensize.X /
3248 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3249 fity_imgsize = padded_screensize.Y /
3250 ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
3253 s32 min_screen_dim = std::min(padded_screensize.X, padded_screensize.Y);
3255 #ifdef HAVE_TOUCHSCREENGUI
3256 // In Android, the preferred imgsize should be larger to accommodate the
3257 // smaller screensize.
3258 double prefer_imgsize = min_screen_dim / 10 * gui_scaling;
3260 // Desktop computers have more space, so try to fit 15 coordinates.
3261 double prefer_imgsize = min_screen_dim / 15 * gui_scaling;
3263 // Try to use the preferred imgsize, but if that's bigger than the maximum
3264 // size, use the maximum size.
3265 use_imgsize = std::min(prefer_imgsize,
3266 std::min(fitx_imgsize, fity_imgsize));
3269 // Everything else is scaled in proportion to the
3270 // inventory image size. The inventory slot spacing
3271 // is 5/4 image size horizontally and 15/13 image size
3272 // vertically. The padding around the form (incorporating
3273 // the border of the outer inventory slots) is 3/8
3274 // image size. Font height (baseline to baseline)
3275 // is 2/5 vertical inventory slot spacing, and button
3276 // half-height is 7/8 of font height.
3277 imgsize = v2s32(use_imgsize, use_imgsize);
3278 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3279 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3280 m_btn_height = use_imgsize*15.0/13 * 0.35;
3282 m_font = g_fontengine->getFont();
3284 if (mydata.real_coordinates) {
3285 mydata.size = v2s32(
3286 mydata.invsize.X*imgsize.X,
3287 mydata.invsize.Y*imgsize.Y
3290 mydata.size = v2s32(
3291 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3292 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3296 DesiredRect = mydata.rect = core::rect<s32>(
3297 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3298 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3299 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3300 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3303 // Non-size[] form must consist only of text fields and
3304 // implicit "Proceed" button. Use default font, and
3305 // temporary form size which will be recalculated below.
3306 m_font = g_fontengine->getFont();
3307 m_btn_height = font_line_height(m_font) * 0.875;
3308 DesiredRect = core::rect<s32>(
3309 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3310 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3311 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3312 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3315 recalculateAbsolutePosition(false);
3316 mydata.basepos = getBasePos();
3317 m_tooltip_element->setOverrideFont(m_font);
3319 gui::IGUISkin *skin = Environment->getSkin();
3321 gui::IGUIFont *old_font = skin->getFont();
3322 skin->setFont(m_font);
3324 // Add a new element that will hold all the background elements as its children.
3325 // Because it is the first added element, all backgrounds will be behind all
3326 // the other elements.
3327 // (We use an arbitrarily big rect. The actual size is determined later by
3328 // clipping to `this`.)
3329 core::rect<s32> background_parent_rect(0, 0, 100000, 100000);
3330 mydata.background_parent.reset(new gui::IGUIElement(EGUIET_ELEMENT, Environment,
3331 this, -1, background_parent_rect));
3333 pos_offset = v2f32();
3335 // used for formspec versions < 3
3336 std::list<IGUIElement *>::iterator legacy_sort_start = std::prev(Children.end()); // last element
3338 if (enable_prepends) {
3339 // Backup the coordinates so that prepends can use the coordinates of choice.
3340 bool rc_backup = mydata.real_coordinates;
3341 u16 version_backup = m_formspec_version;
3342 mydata.real_coordinates = false; // Old coordinates by default.
3344 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3345 for (const auto &element : prepend_elements)
3346 parseElement(&mydata, element);
3348 // legacy sorting for formspec versions < 3
3349 if (m_formspec_version >= 3)
3350 // prepends do not need to be reordered
3351 legacy_sort_start = std::prev(Children.end()); // last element
3352 else if (version_backup >= 3)
3353 // only prepends elements have to be reordered
3354 legacySortElements(legacy_sort_start);
3356 m_formspec_version = version_backup;
3357 mydata.real_coordinates = rc_backup; // Restore coordinates
3360 for (; i< elements.size(); i++) {
3361 parseElement(&mydata, elements[i]);
3364 if (mydata.current_parent != this) {
3365 errorstream << "Invalid formspec string: scroll_container was never closed!"
3367 } else if (!container_stack.empty()) {
3368 errorstream << "Invalid formspec string: container was never closed!"
3372 // get the scrollbar elements for scroll_containers
3373 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3374 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3375 if (c.first == b.first.fname) {
3376 c.second->setScrollBar(b.second);
3382 // If there are fields without explicit size[], add a "Proceed"
3383 // button and adjust size to fit all the fields.
3384 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3385 mydata.rect = core::rect<s32>(
3386 mydata.screensize.X / 2 - 580 / 2,
3387 mydata.screensize.Y / 2 - 300 / 2,
3388 mydata.screensize.X / 2 + 580 / 2,
3389 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3392 DesiredRect = mydata.rect;
3393 recalculateAbsolutePosition(false);
3394 mydata.basepos = getBasePos();
3397 v2s32 pos = mydata.basepos;
3398 pos.Y = (mydata.simple_field_count + 2) * 60;
3400 v2s32 size = DesiredRect.getSize();
3401 mydata.rect = core::rect<s32>(
3402 size.X / 2 - 70, pos.Y,
3403 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3405 const wchar_t *text = wgettext("Proceed");
3406 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3411 // Set initial focus if parser didn't set it
3412 gui::IGUIElement *focused_element = Environment->getFocus();
3413 if (!focused_element
3414 || !isMyChild(focused_element)
3415 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3418 skin->setFont(old_font);
3421 if (m_formspec_version < 3)
3422 legacySortElements(legacy_sort_start);
3424 // Formname and regeneration setting
3425 if (!m_is_form_regenerated) {
3426 // Only set previous form name if we purposefully showed a new formspec
3427 m_last_formname = m_text_dst->m_formname;
3428 m_is_form_regenerated = true;
3432 void GUIFormSpecMenu::legacySortElements(std::list<IGUIElement *>::iterator from)
3435 Draw order for formspec_version <= 2:
3439 0 All other elements
3441 2 item_image, item_image_button
3446 if (from == Children.end())
3447 from = Children.begin();
3451 std::list<IGUIElement *>::iterator to = Children.end();
3452 // 1: Copy into a sortable container
3453 std::vector<IGUIElement *> elements(from, to);
3455 // 2: Sort the container
3456 std::stable_sort(elements.begin(), elements.end(),
3457 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3458 // TODO: getSpecByID is a linear search. It should made O(1), or cached here.
3459 const FieldSpec *spec_a = getSpecByID(a->getID());
3460 const FieldSpec *spec_b = getSpecByID(b->getID());
3461 return spec_a && spec_b &&
3462 spec_a->priority < spec_b->priority;
3465 // 3: Re-assign the pointers
3466 reorderChildren(from, to, elements);
3470 bool GUIFormSpecMenu::getAndroidUIInput()
3472 if (!hasAndroidUIInput())
3476 if (porting::getInputDialogState() == -1)
3479 std::string fieldname = m_jni_field_name;
3480 m_jni_field_name.clear();
3482 for (const FieldSpec &field : m_fields) {
3483 if (field.fname != fieldname)
3486 IGUIElement *element = getElementFromId(field.fid, true);
3488 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3491 std::string text = porting::getInputDialogValue();
3492 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3498 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3500 for (const GUIInventoryList *e : m_inventorylists) {
3501 s32 item_index = e->getItemIndexAtPos(p);
3502 if (item_index != -1)
3503 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3507 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3510 void GUIFormSpecMenu::drawSelectedItem()
3512 video::IVideoDriver* driver = Environment->getVideoDriver();
3514 if (!m_selected_item) {
3515 // reset rotation time
3516 drawItemStack(driver, m_font, ItemStack(),
3517 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3518 m_client, IT_ROT_DRAGGED);
3522 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3524 InventoryList *list = inv->getList(m_selected_item->listname);
3526 ItemStack stack = list->getItem(m_selected_item->i);
3527 stack.count = m_selected_amount;
3529 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3530 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3531 rect.constrainTo(driver->getViewPort());
3532 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3535 void GUIFormSpecMenu::drawMenu()
3538 const std::string &newform = m_form_src->getForm();
3539 if (newform != m_formspec_string) {
3540 m_formspec_string = newform;
3541 m_is_form_regenerated = false;
3542 regenerateGui(m_screensize_old);
3546 gui::IGUISkin* skin = Environment->getSkin();
3547 sanity_check(skin != NULL);
3548 gui::IGUIFont *old_font = skin->getFont();
3549 skin->setFont(m_font);
3551 m_hovered_item_tooltips.clear();
3553 updateSelectedItem();
3555 video::IVideoDriver* driver = Environment->getVideoDriver();
3558 Draw background color
3560 v2u32 screenSize = driver->getScreenSize();
3561 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3564 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3565 if (m_bgnonfullscreen)
3566 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3569 Draw rect_mode tooltip
3571 m_tooltip_element->setVisible(false);
3573 for (const auto &pair : m_tooltip_rects) {
3574 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3575 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3576 const std::wstring &text = pair.second.tooltip;
3577 if (!text.empty()) {
3578 showTooltip(text, pair.second.color, pair.second.bgcolor);
3584 // Some elements are only visible while being drawn
3585 for (gui::IGUIElement *e : m_clickthrough_elements)
3586 e->setVisible(true);
3589 This is where all the drawing happens.
3591 for (auto child : Children)
3592 if (child->isNotClipped() ||
3593 AbsoluteClippingRect.isRectCollided(
3594 child->getAbsolutePosition()))
3597 for (gui::IGUIElement *e : m_clickthrough_elements)
3598 e->setVisible(false);
3600 // Draw hovered item tooltips
3601 for (const std::string &tooltip : m_hovered_item_tooltips) {
3602 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3603 m_default_tooltip_bgcolor);
3606 if (m_hovered_item_tooltips.empty()) {
3607 // reset rotation time
3608 drawItemStack(driver, m_font, ItemStack(),
3609 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3610 NULL, m_client, IT_ROT_HOVERED);
3613 /* TODO find way to show tooltips on touchscreen */
3614 #ifndef HAVE_TOUCHSCREENGUI
3615 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3619 Draw fields/buttons tooltips and update the mouse cursor
3621 gui::IGUIElement *hovered =
3622 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3624 #ifndef HAVE_TOUCHSCREENGUI
3625 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3627 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3629 bool hovered_element_found = false;
3631 if (hovered != NULL) {
3633 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3634 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3637 s32 id = hovered->getID();
3640 m_old_tooltip_id = id;
3642 if (id == m_old_tooltip_id) {
3643 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3645 m_hovered_time = porting::getTimeMs();
3646 m_old_tooltip_id = id;
3650 // Find and update the current tooltip and cursor icon
3652 for (const FieldSpec &field : m_fields) {
3654 if (field.fid != id)
3657 if (delta >= m_tooltip_show_delay) {
3658 const std::wstring &text = m_tooltips[field.fname].tooltip;
3660 showTooltip(text, m_tooltips[field.fname].color,
3661 m_tooltips[field.fname].bgcolor);
3664 #ifndef HAVE_TOUCHSCREENGUI
3665 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3666 current_cursor_icon != field.fcursor_icon)
3667 cursor_control->setActiveIcon(field.fcursor_icon);
3670 hovered_element_found = true;
3677 if (!hovered_element_found) {
3678 // no element is hovered
3679 #ifndef HAVE_TOUCHSCREENGUI
3680 if (current_cursor_icon != ECI_NORMAL)
3681 cursor_control->setActiveIcon(ECI_NORMAL);
3685 m_tooltip_element->draw();
3688 Draw dragged item stack
3692 skin->setFont(old_font);
3696 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3697 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3699 EnrichedString ntext(text);
3700 ntext.setDefaultColor(color);
3701 if (!ntext.hasBackground())
3702 ntext.setBackground(bgcolor);
3704 setStaticText(m_tooltip_element, ntext);
3706 // Tooltip size and offset
3707 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3708 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3710 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3711 int tooltip_offset_x = m_btn_height;
3712 int tooltip_offset_y = m_btn_height;
3713 #ifdef HAVE_TOUCHSCREENGUI
3714 tooltip_offset_x *= 3;
3715 tooltip_offset_y = 0;
3716 if (m_pointer.X > (s32)screenSize.X / 2)
3717 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3719 // Hide tooltip after ETIE_LEFT_UP
3720 if (m_pointer.X == 0)
3724 // Calculate and set the tooltip position
3725 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3726 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3727 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3728 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3729 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3730 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3732 m_tooltip_element->setRelativePosition(
3734 core::position2d<s32>(tooltip_x, tooltip_y),
3735 core::dimension2d<s32>(tooltip_width, tooltip_height)
3739 // Display the tooltip
3740 m_tooltip_element->setVisible(true);
3741 bringToFront(m_tooltip_element);
3744 void GUIFormSpecMenu::updateSelectedItem()
3746 verifySelectedItem();
3748 // If craftresult is nonempty and nothing else is selected, select it now.
3749 if (!m_selected_item) {
3750 for (const GUIInventoryList *e : m_inventorylists) {
3751 if (e->getListname() != "craftpreview")
3754 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3758 InventoryList *list = inv->getList("craftresult");
3760 if (!list || list->getSize() == 0)
3763 const ItemStack &item = list->getItem(0);
3767 // Grab selected item from the crafting result list
3768 m_selected_item = new GUIInventoryList::ItemSpec;
3769 m_selected_item->inventoryloc = e->getInventoryloc();
3770 m_selected_item->listname = "craftresult";
3771 m_selected_item->i = 0;
3772 m_selected_amount = item.count;
3773 m_selected_dragging = false;
3778 // If craftresult is selected, keep the whole stack selected
3779 if (m_selected_item && m_selected_item->listname == "craftresult")
3780 m_selected_amount = verifySelectedItem().count;
3783 ItemStack GUIFormSpecMenu::verifySelectedItem()
3785 // If the selected stack has become empty for some reason, deselect it.
3786 // If the selected stack has become inaccessible, deselect it.
3787 // If the selected stack has become smaller, adjust m_selected_amount.
3788 // Return the selected stack.
3790 if (m_selected_item) {
3791 if (m_selected_item->isValid()) {
3792 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3794 InventoryList *list = inv->getList(m_selected_item->listname);
3795 if (list && (u32) m_selected_item->i < list->getSize()) {
3796 ItemStack stack = list->getItem(m_selected_item->i);
3797 if (!m_selected_swap.empty()) {
3798 if (m_selected_swap.name == stack.name &&
3799 m_selected_swap.count == stack.count)
3800 m_selected_swap.clear();
3802 m_selected_amount = std::min(m_selected_amount, stack.count);
3811 // selection was not valid
3812 delete m_selected_item;
3813 m_selected_item = nullptr;
3814 m_selected_amount = 0;
3815 m_selected_dragging = false;
3820 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
3826 if (quitmode == quit_mode_accept) {
3827 fields["quit"] = "true";
3830 if (quitmode == quit_mode_cancel) {
3831 fields["quit"] = "true";
3832 m_text_dst->gotText(fields);
3836 if (current_keys_pending.key_down) {
3837 fields["key_down"] = "true";
3838 current_keys_pending.key_down = false;
3841 if (current_keys_pending.key_up) {
3842 fields["key_up"] = "true";
3843 current_keys_pending.key_up = false;
3846 if (current_keys_pending.key_enter) {
3847 fields["key_enter"] = "true";
3848 current_keys_pending.key_enter = false;
3851 if (!current_field_enter_pending.empty()) {
3852 fields["key_enter_field"] = current_field_enter_pending;
3853 current_field_enter_pending = "";
3856 if (current_keys_pending.key_escape) {
3857 fields["key_escape"] = "true";
3858 current_keys_pending.key_escape = false;
3861 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3863 std::string name = s.fname;
3864 if (s.ftype == f_Button) {
3865 fields[name] = wide_to_utf8(s.flabel);
3866 } else if (s.ftype == f_Table) {
3867 GUITable *table = getTable(s.fname);
3869 fields[name] = table->checkEvent();
3871 } else if (s.ftype == f_DropDown) {
3872 // No dynamic cast possible due to some distributions shipped
3873 // without rtti support in Irrlicht
3874 IGUIElement *element = getElementFromId(s.fid, true);
3875 gui::IGUIComboBox *e = NULL;
3876 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3877 e = static_cast<gui::IGUIComboBox *>(element);
3879 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3880 << "field without dropdown element" << std::endl;
3883 s32 selected = e->getSelected();
3884 if (selected >= 0) {
3885 if (m_dropdown_index_event.find(s.fname) !=
3886 m_dropdown_index_event.end()) {
3887 fields[name] = std::to_string(selected + 1);
3889 std::vector<std::string> *dropdown_values =
3890 getDropDownValues(s.fname);
3891 if (dropdown_values && selected < (s32)dropdown_values->size())
3892 fields[name] = (*dropdown_values)[selected];
3895 } else if (s.ftype == f_TabHeader) {
3896 // No dynamic cast possible due to some distributions shipped
3897 // without rtti support in Irrlicht
3898 IGUIElement *element = getElementFromId(s.fid, true);
3899 gui::IGUITabControl *e = nullptr;
3900 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3901 e = static_cast<gui::IGUITabControl *>(element);
3905 fields[name] = itos(e->getActiveTab() + 1);
3907 } else if (s.ftype == f_CheckBox) {
3908 // No dynamic cast possible due to some distributions shipped
3909 // without rtti support in Irrlicht
3910 IGUIElement *element = getElementFromId(s.fid, true);
3911 gui::IGUICheckBox *e = nullptr;
3912 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3913 e = static_cast<gui::IGUICheckBox*>(element);
3918 fields[name] = "true";
3920 fields[name] = "false";
3922 } else if (s.ftype == f_ScrollBar) {
3923 // No dynamic cast possible due to some distributions shipped
3924 // without rtti support in Irrlicht
3925 IGUIElement *element = getElementFromId(s.fid, true);
3926 GUIScrollBar *e = nullptr;
3927 if (element && element->getType() == gui::EGUIET_ELEMENT)
3928 e = static_cast<GUIScrollBar *>(element);
3931 if (s.fdefault == L"Changed")
3932 fields[name] = "CHG:" + itos(e->getPos());
3934 fields[name] = "VAL:" + itos(e->getPos());
3936 } else if (s.ftype == f_AnimatedImage) {
3937 // No dynamic cast possible due to some distributions shipped
3938 // without rtti support in Irrlicht
3939 IGUIElement *element = getElementFromId(s.fid, true);
3940 GUIAnimatedImage *e = nullptr;
3941 if (element && element->getType() == gui::EGUIET_ELEMENT)
3942 e = static_cast<GUIAnimatedImage *>(element);
3945 fields[name] = std::to_string(e->getFrameIndex() + 1);
3947 IGUIElement *e = getElementFromId(s.fid, true);
3949 fields[name] = wide_to_utf8(e->getText());
3954 m_text_dst->gotText(fields);
3958 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3960 // The IGUITabControl renders visually using the skin's selected
3961 // font, which we override for the duration of form drawing,
3962 // but computes tab hotspots based on how it would have rendered
3963 // using the font that is selected at the time of button release.
3964 // To make these two consistent, temporarily override the skin's
3965 // font while the IGUITabControl is processing the event.
3966 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3967 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3968 s32 x = event.MouseInput.X;
3969 s32 y = event.MouseInput.Y;
3970 gui::IGUIElement *hovered =
3971 Environment->getRootGUIElement()->getElementFromPoint(
3972 core::position2d<s32>(x, y));
3973 if (hovered && isMyChild(hovered) &&
3974 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3975 gui::IGUISkin* skin = Environment->getSkin();
3976 sanity_check(skin != NULL);
3977 gui::IGUIFont *old_font = skin->getFont();
3978 skin->setFont(m_font);
3979 bool retval = hovered->OnEvent(event);
3980 skin->setFont(old_font);
3985 // Fix Esc/Return key being eaten by checkboxen and tables
3986 if (event.EventType == EET_KEY_INPUT_EVENT) {
3987 KeyPress kp(event.KeyInput);
3988 if (kp == EscapeKey || kp == CancelKey
3989 || kp == getKeySetting("keymap_inventory")
3990 || event.KeyInput.Key==KEY_RETURN) {
3991 gui::IGUIElement *focused = Environment->getFocus();
3992 if (focused && isMyChild(focused) &&
3993 (focused->getType() == gui::EGUIET_LIST_BOX ||
3994 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3995 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3996 event.KeyInput.Key != KEY_RETURN)) {
4002 // Mouse wheel and move events: send to hovered element instead of focused
4003 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4004 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
4005 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4006 event.MouseInput.ButtonStates == 0))) {
4007 s32 x = event.MouseInput.X;
4008 s32 y = event.MouseInput.Y;
4009 gui::IGUIElement *hovered =
4010 Environment->getRootGUIElement()->getElementFromPoint(
4011 core::position2d<s32>(x, y));
4012 if (hovered && isMyChild(hovered)) {
4013 hovered->OnEvent(event);
4014 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
4018 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
4019 /* TODO add a check like:
4020 if (event.JoystickEvent != joystick_we_listen_for)
4023 bool handled = m_joystick->handleEvent(event.JoystickEvent);
4025 if (m_joystick->wasKeyDown(KeyType::ESC)) {
4027 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
4029 acceptInput(quit_mode_accept);
4037 return GUIModalMenu::preprocessEvent(event);
4040 void GUIFormSpecMenu::tryClose()
4044 acceptInput(quit_mode_cancel);
4047 m_text_dst->gotText(L"MenuQuit");
4051 enum ButtonEventType : u8
4064 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
4066 if (event.EventType==EET_KEY_INPUT_EVENT) {
4067 KeyPress kp(event.KeyInput);
4068 if (event.KeyInput.PressedDown && (
4069 (kp == EscapeKey) || (kp == CancelKey) ||
4070 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4075 if (m_client != NULL && event.KeyInput.PressedDown &&
4076 (kp == getKeySetting("keymap_screenshot"))) {
4077 m_client->makeScreenshot();
4080 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4081 m_show_debug = !m_show_debug;
4083 if (event.KeyInput.PressedDown &&
4084 (event.KeyInput.Key==KEY_RETURN ||
4085 event.KeyInput.Key==KEY_UP ||
4086 event.KeyInput.Key==KEY_DOWN)
4088 switch (event.KeyInput.Key) {
4090 current_keys_pending.key_enter = true;
4093 current_keys_pending.key_up = true;
4096 current_keys_pending.key_down = true;
4100 //can't happen at all!
4101 FATAL_ERROR("Reached a source line that can't ever been reached");
4104 if (current_keys_pending.key_enter && m_allowclose) {
4105 acceptInput(quit_mode_accept);
4115 /* Mouse event other than movement, or crossing the border of inventory
4116 field while holding right mouse button
4118 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4119 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4120 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4121 event.MouseInput.isRightPressed() &&
4122 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4124 // Get selected item and hovered/clicked item (s)
4126 m_old_tooltip_id = -1;
4127 updateSelectedItem();
4128 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4130 Inventory *inv_selected = NULL;
4131 Inventory *inv_s = NULL;
4132 InventoryList *list_s = NULL;
4134 if (m_selected_item) {
4135 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4136 sanity_check(inv_selected);
4137 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4144 inv_s = m_invmgr->getInventory(s.inventoryloc);
4147 errorstream << "InventoryMenu: The selected inventory location "
4148 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4150 s.i = -1; // make it invalid again
4154 list_s = inv_s->getList(s.listname);
4155 if (list_s == NULL) {
4156 verbosestream << "InventoryMenu: The selected inventory list \""
4157 << s.listname << "\" does not exist" << std::endl;
4158 s.i = -1; // make it invalid again
4162 if ((u32)s.i >= list_s->getSize()) {
4163 infostream << "InventoryMenu: The selected inventory list \""
4164 << s.listname << "\" is too small (i=" << s.i << ", size="
4165 << list_s->getSize() << ")" << std::endl;
4166 s.i = -1; // make it invalid again
4170 s_count = list_s->getItem(s.i).count;
4173 bool identical = m_selected_item && s.isValid() &&
4174 (inv_selected == inv_s) &&
4175 (m_selected_item->listname == s.listname) &&
4176 (m_selected_item->i == s.i);
4178 ButtonEventType button = BET_LEFT;
4179 ButtonEventType updown = BET_OTHER;
4180 switch (event.MouseInput.Event) {
4181 case EMIE_LMOUSE_PRESSED_DOWN:
4182 button = BET_LEFT; updown = BET_DOWN;
4184 case EMIE_RMOUSE_PRESSED_DOWN:
4185 button = BET_RIGHT; updown = BET_DOWN;
4187 case EMIE_MMOUSE_PRESSED_DOWN:
4188 button = BET_MIDDLE; updown = BET_DOWN;
4190 case EMIE_MOUSE_WHEEL:
4191 button = (event.MouseInput.Wheel > 0) ?
4192 BET_WHEEL_UP : BET_WHEEL_DOWN;
4195 case EMIE_LMOUSE_LEFT_UP:
4196 button = BET_LEFT; updown = BET_UP;
4198 case EMIE_RMOUSE_LEFT_UP:
4199 button = BET_RIGHT; updown = BET_UP;
4201 case EMIE_MMOUSE_LEFT_UP:
4202 button = BET_MIDDLE; updown = BET_UP;
4204 case EMIE_MOUSE_MOVED:
4211 // Set this number to a positive value to generate a move action
4212 // from m_selected_item to s.
4213 u32 move_amount = 0;
4215 // Set this number to a positive value to generate a move action
4216 // from s to the next inventory ring.
4217 u32 shift_move_amount = 0;
4219 // Set this number to a positive value to generate a drop action
4220 // from m_selected_item.
4221 u32 drop_amount = 0;
4223 // Set this number to a positive value to generate a craft action at s.
4224 u32 craft_amount = 0;
4228 // Some mouse button has been pressed
4230 //infostream << "Mouse button " << button << " pressed at p=("
4231 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4234 m_selected_dragging = false;
4236 if (s.isValid() && s.listname == "craftpreview") {
4237 // Craft preview has been clicked: craft
4238 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4239 } else if (!m_selected_item) {
4240 if (s_count && button != BET_WHEEL_UP) {
4241 // Non-empty stack has been clicked: select or shift-move it
4242 m_selected_item = new GUIInventoryList::ItemSpec(s);
4245 if (button == BET_RIGHT)
4246 count = (s_count + 1) / 2;
4247 else if (button == BET_MIDDLE)
4248 count = MYMIN(s_count, 10);
4249 else if (button == BET_WHEEL_DOWN)
4254 if (!event.MouseInput.Shift) {
4255 // no shift: select item
4256 m_selected_amount = count;
4257 m_selected_dragging = button != BET_WHEEL_DOWN;
4258 m_auto_place = false;
4260 // shift pressed: move item, right click moves 1
4261 shift_move_amount = button == BET_RIGHT ? 1 : count;
4264 } else { // m_selected_item != NULL
4265 assert(m_selected_amount >= 1);
4268 // Clicked a slot: move
4269 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4271 else if (button == BET_MIDDLE)
4272 move_amount = MYMIN(m_selected_amount, 10);
4273 else if (button == BET_LEFT)
4274 move_amount = m_selected_amount;
4278 if (button == BET_WHEEL_DOWN) {
4279 if (m_selected_amount < s_count)
4280 ++m_selected_amount;
4282 if (move_amount >= m_selected_amount)
4283 m_selected_amount = 0;
4285 m_selected_amount -= move_amount;
4289 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4290 && button != BET_WHEEL_DOWN) {
4291 // Clicked outside of the window: drop
4292 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4294 else if (button == BET_MIDDLE)
4295 drop_amount = MYMIN(m_selected_amount, 10);
4297 drop_amount = m_selected_amount;
4302 // Some mouse button has been released
4304 //infostream<<"Mouse button "<<button<<" released at p=("
4305 // <<p.X<<","<<p.Y<<")"<<std::endl;
4307 if (m_selected_dragging && m_selected_item) {
4310 // Dragged to different slot: move all selected
4311 move_amount = m_selected_amount;
4313 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4314 // Dragged outside of window: drop all selected
4315 drop_amount = m_selected_amount;
4319 m_selected_dragging = false;
4320 // Keep track of whether the mouse button be released
4321 // One click is drag without dropping. Click + release
4322 // + click changes to drop item when moved mode
4323 if (m_selected_item)
4324 m_auto_place = true;
4327 // Mouse has been moved and rmb is down and mouse pointer just
4328 // entered a new inventory field (checked in the entry-if, this
4329 // is the only action here that is generated by mouse movement)
4330 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4332 // TODO: middle mouse to move 10 items might be handy
4334 // Only move an item if the destination slot is empty
4335 // or contains the same item type as what is going to be
4337 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4338 InventoryList *list_to = list_s;
4339 assert(list_from && list_to);
4340 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4341 ItemStack stack_to = list_to->getItem(s.i);
4342 if (stack_to.empty() || stack_to.name == stack_from.name)
4351 // Possibly send inventory action to server
4352 if (move_amount > 0) {
4353 // Send IAction::Move
4355 assert(m_selected_item && m_selected_item->isValid());
4356 assert(s.isValid());
4358 assert(inv_selected && inv_s);
4359 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4360 InventoryList *list_to = list_s;
4361 assert(list_from && list_to);
4362 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4363 ItemStack stack_to = list_to->getItem(s.i);
4365 // Check how many items can be moved
4366 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4367 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4369 // If source stack cannot be added to destination stack at all,
4371 if (leftover.count == stack_from.count &&
4372 leftover.name == stack_from.name) {
4374 if (m_selected_swap.empty()) {
4375 m_selected_amount = stack_to.count;
4376 m_selected_dragging = false;
4378 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4379 // Skip next validation checks due async inventory calls
4380 m_selected_swap = stack_to;
4385 // Source stack goes fully into destination stack
4386 else if (leftover.empty()) {
4387 m_selected_amount -= move_amount;
4389 // Source stack goes partly into destination stack
4391 move_amount -= leftover.count;
4392 m_selected_amount -= move_amount;
4396 infostream << "Handing IAction::Move to manager" << std::endl;
4397 IMoveAction *a = new IMoveAction();
4398 a->count = move_amount;
4399 a->from_inv = m_selected_item->inventoryloc;
4400 a->from_list = m_selected_item->listname;
4401 a->from_i = m_selected_item->i;
4402 a->to_inv = s.inventoryloc;
4403 a->to_list = s.listname;
4405 m_invmgr->inventoryAction(a);
4407 } else if (shift_move_amount > 0) {
4408 u32 mis = m_inventory_rings.size();
4410 for (; i < mis; i++) {
4411 const ListRingSpec &sp = m_inventory_rings[i];
4412 if (sp.inventoryloc == s.inventoryloc
4413 && sp.listname == s.listname)
4417 if (i >= mis) // if not found
4419 u32 to_inv_ind = (i + 1) % mis;
4420 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4421 InventoryList *list_from = list_s;
4424 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4427 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4430 ItemStack stack_from = list_from->getItem(s.i);
4431 assert(shift_move_amount <= stack_from.count);
4433 infostream << "Handing IAction::Move to manager" << std::endl;
4434 IMoveAction *a = new IMoveAction();
4435 a->count = shift_move_amount;
4436 a->from_inv = s.inventoryloc;
4437 a->from_list = s.listname;
4439 a->to_inv = to_inv_sp.inventoryloc;
4440 a->to_list = to_inv_sp.listname;
4441 a->move_somewhere = true;
4442 m_invmgr->inventoryAction(a);
4444 } else if (drop_amount > 0) {
4445 // Send IAction::Drop
4447 assert(m_selected_item && m_selected_item->isValid());
4448 assert(inv_selected);
4449 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4451 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4453 // Check how many items can be dropped
4454 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4455 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4456 m_selected_amount -= drop_amount;
4458 infostream << "Handing IAction::Drop to manager" << std::endl;
4459 IDropAction *a = new IDropAction();
4460 a->count = drop_amount;
4461 a->from_inv = m_selected_item->inventoryloc;
4462 a->from_list = m_selected_item->listname;
4463 a->from_i = m_selected_item->i;
4464 m_invmgr->inventoryAction(a);
4465 } else if (craft_amount > 0) {
4466 assert(s.isValid());
4468 // if there are no items selected or the selected item
4469 // belongs to craftresult list, proceed with crafting
4470 if (!m_selected_item ||
4471 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4475 // Send IACTION_CRAFT
4476 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4477 ICraftAction *a = new ICraftAction();
4478 a->count = craft_amount;
4479 a->craft_inv = s.inventoryloc;
4480 m_invmgr->inventoryAction(a);
4484 // If m_selected_amount has been decreased to zero, deselect
4485 if (m_selected_amount == 0) {
4486 m_selected_swap.clear();
4487 delete m_selected_item;
4488 m_selected_item = nullptr;
4489 m_selected_amount = 0;
4490 m_selected_dragging = false;
4492 m_old_pointer = m_pointer;
4495 if (event.EventType == EET_GUI_EVENT) {
4496 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4498 // find the element that was clicked
4499 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4500 if ((s.ftype == f_TabHeader) &&
4501 (s.fid == event.GUIEvent.Caller->getID())) {
4502 if (!s.sound.empty() && m_sound_manager)
4503 m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
4511 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4513 if (!canTakeFocus(event.GUIEvent.Element)) {
4514 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4516 // Returning true disables focus change
4520 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4521 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4522 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4523 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4524 s32 caller_id = event.GUIEvent.Caller->getID();
4526 if (caller_id == 257) {
4528 acceptInput(quit_mode_accept);
4532 m_text_dst->gotText(L"ExitButton");
4534 // quitMenu deallocates menu
4538 // find the element that was clicked
4539 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4540 // if its a button, set the send field so
4541 // lua knows which button was pressed
4543 if (caller_id != s.fid)
4546 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4547 if (!s.sound.empty() && m_sound_manager)
4548 m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
4553 acceptInput(quit_mode_accept);
4556 m_text_dst->gotText(L"ExitButton");
4561 acceptInput(quit_mode_no);
4565 } else if (s.ftype == f_DropDown) {
4566 // only send the changed dropdown
4567 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4568 if (s2.ftype == f_DropDown) {
4572 if (!s.sound.empty() && m_sound_manager)
4573 m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
4575 acceptInput(quit_mode_no);
4577 // revert configuration to make sure dropdowns are sent on
4578 // regular button click
4579 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4580 if (s2.ftype == f_DropDown) {
4585 } else if (s.ftype == f_ScrollBar) {
4586 s.fdefault = L"Changed";
4587 acceptInput(quit_mode_no);
4589 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4590 if (!s.sound.empty() && m_sound_manager)
4591 m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
4599 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4600 // move scroll_containers
4601 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4602 c.second->onScrollEvent(event.GUIEvent.Caller);
4605 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4606 if (event.GUIEvent.Caller->getID() > 257) {
4607 bool close_on_enter = true;
4608 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4609 if (s.ftype == f_Unknown &&
4610 s.fid == event.GUIEvent.Caller->getID()) {
4611 current_field_enter_pending = s.fname;
4612 std::unordered_map<std::string, bool>::const_iterator it =
4613 field_close_on_enter.find(s.fname);
4614 if (it != field_close_on_enter.end())
4615 close_on_enter = (*it).second;
4621 if (m_allowclose && close_on_enter) {
4622 current_keys_pending.key_enter = true;
4623 acceptInput(quit_mode_accept);
4626 current_keys_pending.key_enter = true;
4629 // quitMenu deallocates menu
4634 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4635 int current_id = event.GUIEvent.Caller->getID();
4636 if (current_id > 257) {
4637 // find the element that was clicked
4638 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4639 // if it's a table, set the send field
4640 // so lua knows which table was changed
4641 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4652 return Parent ? Parent->OnEvent(event) : false;
4656 * get name of element by element id
4657 * @param id of element
4658 * @return name string or empty string
4660 std::string GUIFormSpecMenu::getNameByID(s32 id)
4662 for (FieldSpec &spec : m_fields) {
4670 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4672 for (FieldSpec &spec : m_fields) {
4680 * get label of element by id
4681 * @param id of element
4682 * @return label string or empty string
4684 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4686 for (FieldSpec &spec : m_fields) {
4693 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4694 const std::string &name, const std::string &parent_type) {
4695 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4698 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4699 const std::string &type, const std::string &name, const std::string &parent_type)
4701 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4703 auto it = theme_by_type.find("*");
4704 if (it != theme_by_type.end()) {
4705 for (const StyleSpec &spec : it->second)
4706 ret[(u32)spec.getState()] |= spec;
4709 it = theme_by_name.find("*");
4710 if (it != theme_by_name.end()) {
4711 for (const StyleSpec &spec : it->second)
4712 ret[(u32)spec.getState()] |= spec;
4715 if (!parent_type.empty()) {
4716 it = theme_by_type.find(parent_type);
4717 if (it != theme_by_type.end()) {
4718 for (const StyleSpec &spec : it->second)
4719 ret[(u32)spec.getState()] |= spec;
4723 it = theme_by_type.find(type);
4724 if (it != theme_by_type.end()) {
4725 for (const StyleSpec &spec : it->second)
4726 ret[(u32)spec.getState()] |= spec;
4729 it = theme_by_name.find(name);
4730 if (it != theme_by_name.end()) {
4731 for (const StyleSpec &spec : it->second)
4732 ret[(u32)spec.getState()] |= spec;