3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "guiFormSpecMenu.h"
27 #include "guiScrollBar.h"
29 #include "constants.h"
31 #include "client/keycode.h"
32 #include "util/strfnd.h"
33 #include <IGUIButton.h>
34 #include <IGUICheckBox.h>
35 #include <IGUIComboBox.h>
36 #include <IGUIEditBox.h>
37 #include <IGUIStaticText.h>
39 #include <IGUITabControl.h>
40 #include "client/renderingengine.h"
42 #include "client/tile.h" // ITextureSource
43 #include "client/hud.h" // drawItemStack
47 #include "scripting_server.h"
48 #include "mainmenumanager.h"
51 #include "client/client.h"
52 #include "client/fontengine.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "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 "guiScrollBar.h"
68 #include "guiScrollContainer.h"
70 #include "intlGUIEditBox.h"
71 #include "guiHyperText.h"
73 #define MY_CHECKPOS(a,b) \
74 if (v_pos.size() != 2) { \
75 errorstream<< "Invalid pos for element " << a << "specified: \"" \
76 << parts[b] << "\"" << std::endl; \
80 #define MY_CHECKGEOM(a,b) \
81 if (v_geom.size() != 2) { \
82 errorstream<< "Invalid geometry for element " << a << \
83 "specified: \"" << parts[b] << "\"" << std::endl; \
89 static unsigned int font_line_height(gui::IGUIFont *font)
91 return font->getDimension(L"Ay").Height + font->getKerningHeight();
94 inline u32 clamp_u8(s32 value)
96 return (u32) MYMIN(MYMAX(value, 0), 255);
99 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
100 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
101 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
102 const std::string &formspecPrepend,
103 bool remap_dbl_click):
104 GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
108 m_formspec_prepend(formspecPrepend),
111 m_joystick(joystick),
112 m_remap_dbl_click(remap_dbl_click)
114 current_keys_pending.key_down = false;
115 current_keys_pending.key_up = false;
116 current_keys_pending.key_enter = false;
117 current_keys_pending.key_escape = false;
119 m_doubleclickdetect[0].time = 0;
120 m_doubleclickdetect[1].time = 0;
122 m_doubleclickdetect[0].pos = v2s32(0, 0);
123 m_doubleclickdetect[1].pos = v2s32(0, 0);
125 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
126 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
129 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 &background_it : m_backgrounds)
142 background_it->drop();
143 for (auto &tooltip_rect_it : m_tooltip_rects)
144 tooltip_rect_it.first->drop();
145 for (auto &clickthrough_it : m_clickthrough_elements)
146 clickthrough_it->drop();
147 for (auto &scroll_container_it : m_scroll_containers)
148 scroll_container_it.second->drop();
150 delete m_selected_item;
155 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
156 JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
157 const std::string &formspecPrepend)
159 if (cur_formspec == nullptr) {
160 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
161 client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
162 cur_formspec->doPause = false;
165 Caution: do not call (*cur_formspec)->drop() here --
166 the reference might outlive the menu, so we will
167 periodically check if *cur_formspec is the only
168 remaining reference (i.e. the menu was removed)
169 and delete it in that case.
173 cur_formspec->setFormspecPrepend(formspecPrepend);
174 cur_formspec->setFormSource(fs_src);
175 cur_formspec->setTextDest(txt_dest);
179 void GUIFormSpecMenu::removeChildren()
181 const core::list<gui::IGUIElement*> &children = getChildren();
183 while (!children.empty()) {
184 (*children.getLast())->remove();
187 if (m_tooltip_element) {
188 m_tooltip_element->remove();
189 m_tooltip_element->drop();
190 m_tooltip_element = nullptr;
194 void GUIFormSpecMenu::setInitialFocus()
196 // Set initial focus according to following order of precedence:
197 // 1. first empty editbox
201 // 5. first focusable (not statictext, not tabheader)
202 // 6. first child element
204 core::list<gui::IGUIElement*> children = getChildren();
206 // in case "children" contains any NULL elements, remove them
207 for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
208 it != children.end();) {
212 it = children.erase(it);
215 // 1. first empty editbox
216 for (gui::IGUIElement *it : children) {
217 if (it->getType() == gui::EGUIET_EDIT_BOX
218 && it->getText()[0] == 0) {
219 Environment->setFocus(it);
225 for (gui::IGUIElement *it : children) {
226 if (it->getType() == gui::EGUIET_EDIT_BOX) {
227 Environment->setFocus(it);
233 for (gui::IGUIElement *it : children) {
234 if (it->getTypeName() == std::string("GUITable")) {
235 Environment->setFocus(it);
241 for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
242 it != children.end(); --it) {
243 if ((*it)->getType() == gui::EGUIET_BUTTON) {
244 Environment->setFocus(*it);
249 // 5. first focusable (not statictext, not tabheader)
250 for (gui::IGUIElement *it : children) {
251 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
252 it->getType() != gui::EGUIET_TAB_CONTROL) {
253 Environment->setFocus(it);
258 // 6. first child element
259 if (children.empty())
260 Environment->setFocus(this);
262 Environment->setFocus(*(children.begin()));
265 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
267 for (auto &table : m_tables) {
268 if (tablename == table.first.fname)
274 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
276 for (auto &dropdown : m_dropdowns) {
277 if (name == dropdown.first.fname)
278 return &dropdown.second;
283 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
285 v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
287 pos_f.X += stof((*v_pos)[0]) * spacing.X;
288 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
290 return v2s32(pos_f.X, pos_f.Y);
293 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
295 return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
296 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
299 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
301 return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
304 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
306 std::vector<std::string> parts = split(element,',');
308 if (((parts.size() == 2) || parts.size() == 3) ||
309 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
311 if (parts[1].find(';') != std::string::npos)
312 parts[1] = parts[1].substr(0,parts[1].find(';'));
314 data->invsize.X = MYMAX(0, stof(parts[0]));
315 data->invsize.Y = MYMAX(0, stof(parts[1]));
319 if (parts.size() == 3) {
320 if (parts[2] == "true") {
321 lockSize(true,v2u32(800,600));
325 data->explicit_size = true;
328 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
331 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
333 std::vector<std::string> parts = split(element, ',');
335 if (parts.size() >= 2) {
336 if (parts[1].find(';') != std::string::npos)
337 parts[1] = parts[1].substr(0, parts[1].find(';'));
339 container_stack.push(pos_offset);
340 pos_offset.X += stof(parts[0]);
341 pos_offset.Y += stof(parts[1]);
344 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
347 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
349 if (container_stack.empty()) {
350 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
352 pos_offset = container_stack.top();
353 container_stack.pop();
357 void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
359 std::vector<std::string> parts = split(element, ';');
361 if (parts.size() < 4 ||
362 (parts.size() > 5 && m_formspec_version <= FORMSPEC_API_VERSION)) {
363 errorstream << "Invalid scroll_container start element (" << parts.size()
364 << "): '" << element << "'" << std::endl;
368 std::vector<std::string> v_pos = split(parts[0], ',');
369 std::vector<std::string> v_geom = split(parts[1], ',');
370 std::string scrollbar_name = parts[2];
371 std::string orientation = parts[3];
372 f32 scroll_factor = 0.1f;
373 if (parts.size() >= 5 && !parts[4].empty())
374 scroll_factor = stof(parts[4]);
376 MY_CHECKPOS("scroll_container", 0);
377 MY_CHECKGEOM("scroll_container", 1);
379 v2s32 pos = getRealCoordinateBasePos(v_pos);
380 v2s32 geom = getRealCoordinateGeometry(v_geom);
382 if (orientation == "vertical")
383 scroll_factor *= -imgsize.Y;
384 else if (orientation == "horizontal")
385 scroll_factor *= -imgsize.X;
387 warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
388 << "Invalid scroll_container orientation: " << orientation
391 // old parent (at first: this)
392 // ^ is parent of clipper
393 // ^ is parent of mover
394 // ^ is parent of other elements
397 core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
399 gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
400 data->current_parent, 0, rect_clipper);
403 FieldSpec spec_mover(
407 258 + m_fields.size()
410 core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
412 GUIScrollContainer *mover = new GUIScrollContainer(Environment,
413 clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
415 data->current_parent = mover;
417 m_scroll_containers.emplace_back(scrollbar_name, mover);
419 m_fields.push_back(spec_mover);
423 // remove interferring offset of normal containers
424 container_stack.push(pos_offset);
429 void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
431 if (data->current_parent == this || data->current_parent->getParent() == this ||
432 container_stack.empty()) {
433 errorstream << "Invalid scroll_container end element, "
434 << "no matching scroll_container start element" << std::endl;
438 if (pos_offset.getLengthSQ() != 0.0f) {
439 // pos_offset is only set by containers and scroll_containers.
440 // scroll_containers always set it to 0,0 which means that if it is
441 // not 0,0, it is a normal container that was opened last, not a
443 errorstream << "Invalid scroll_container end element, "
444 << "an inner container was left open" << std::endl;
448 data->current_parent = data->current_parent->getParent()->getParent();
449 pos_offset = container_stack.top();
450 container_stack.pop();
453 void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
456 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
460 std::vector<std::string> parts = split(element,';');
462 if (((parts.size() == 4) || (parts.size() == 5)) ||
463 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
465 std::string location = parts[0];
466 std::string listname = parts[1];
467 std::vector<std::string> v_pos = split(parts[2],',');
468 std::vector<std::string> v_geom = split(parts[3],',');
469 std::string startindex;
470 if (parts.size() == 5)
471 startindex = parts[4];
473 MY_CHECKPOS("list",2);
474 MY_CHECKGEOM("list",3);
476 InventoryLocation loc;
478 if (location == "context" || location == "current_name")
479 loc = m_current_inventory_location;
481 loc.deSerialize(location);
484 geom.X = stoi(v_geom[0]);
485 geom.Y = stoi(v_geom[1]);
488 if (!startindex.empty())
489 start_i = stoi(startindex);
491 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
492 errorstream << "Invalid list element: '" << element << "'" << std::endl;
496 if (!data->explicit_size)
497 warningstream << "invalid use of list without a size[] element" << std::endl;
503 258 + m_fields.size(),
507 v2f32 slot_spacing = data->real_coordinates ?
508 v2f32(imgsize.X * 1.25f, imgsize.Y * 1.25f) : spacing;
510 v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos)
511 : getElementBasePos(&v_pos);
513 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
514 pos.X + (geom.X - 1) * slot_spacing.X + imgsize.X,
515 pos.Y + (geom.Y - 1) * slot_spacing.Y + imgsize.Y);
517 GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
518 spec.fid, rect, m_invmgr, loc, listname, geom, start_i, imgsize,
519 slot_spacing, this, data->inventorylist_options, m_font);
521 m_inventorylists.push_back(e);
522 m_fields.push_back(spec);
525 errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl;
528 void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
531 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
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 = split(element,';');
570 if (((parts.size() >= 3) && (parts.size() <= 4)) ||
571 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
573 std::vector<std::string> v_pos = split(parts[0],',');
574 std::string name = parts[1];
575 std::string label = parts[2];
576 std::string selected;
578 if (parts.size() >= 4)
581 MY_CHECKPOS("checkbox",0);
583 bool fselected = false;
585 if (selected == "true")
588 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
589 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
590 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
591 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
594 core::rect<s32> rect;
596 if (data->real_coordinates) {
597 pos = getRealCoordinateBasePos(v_pos);
599 rect = core::rect<s32>(
602 pos.X + label_size.Width + cb_size + 7,
606 pos = getElementBasePos(&v_pos);
607 rect = core::rect<s32>(
609 pos.Y + imgsize.Y / 2 - y_center,
610 pos.X + label_size.Width + cb_size + 7,
611 pos.Y + imgsize.Y / 2 + y_center
617 wlabel, //Needed for displaying text on MSVC
622 spec.ftype = f_CheckBox;
624 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
625 data->current_parent, spec.fid, spec.flabel.c_str());
627 auto style = getDefaultStyleForElement("checkbox", name);
628 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
630 if (spec.fname == data->focused_fieldname) {
631 Environment->setFocus(e);
635 m_checkboxes.emplace_back(spec, e);
636 m_fields.push_back(spec);
639 errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl;
642 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
644 std::vector<std::string> parts = split(element,';');
646 if (parts.size() >= 5) {
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 m_scrollbars.emplace_back(spec,e);
707 m_fields.push_back(spec);
710 errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element
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 = split(element,';');
771 if ((parts.size() == 3) ||
772 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
774 std::vector<std::string> v_pos = split(parts[0],',');
775 std::vector<std::string> v_geom = split(parts[1],',');
776 std::string name = unescape_string(parts[2]);
778 MY_CHECKPOS("image", 0);
779 MY_CHECKGEOM("image", 1);
784 if (data->real_coordinates) {
785 pos = getRealCoordinateBasePos(v_pos);
786 geom = getRealCoordinateGeometry(v_geom);
788 pos = getElementBasePos(&v_pos);
789 geom.X = stof(v_geom[0]) * (float)imgsize.X;
790 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
793 if (!data->explicit_size)
794 warningstream<<"invalid use of image without a size[] element"<<std::endl;
796 video::ITexture *texture = m_tsrc->getTexture(name);
798 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
799 << std::endl << "\t" << name << std::endl;
807 258 + m_fields.size(),
810 core::rect<s32> rect(pos, pos + geom);
811 gui::IGUIImage *e = Environment->addImage(rect, data->current_parent,
813 e->setImage(texture);
814 e->setScaleImage(true);
815 auto style = getDefaultStyleForElement("image", spec.fname);
816 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
817 m_fields.push_back(spec);
819 // images should let events through
821 m_clickthrough_elements.push_back(e);
825 if (parts.size() == 2) {
826 std::vector<std::string> v_pos = split(parts[0],',');
827 std::string name = unescape_string(parts[1]);
829 MY_CHECKPOS("image", 0);
831 v2s32 pos = getElementBasePos(&v_pos);
833 if (!data->explicit_size)
834 warningstream<<"invalid use of image without a size[] element"<<std::endl;
836 video::ITexture *texture = m_tsrc->getTexture(name);
838 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
839 << std::endl << "\t" << name << std::endl;
847 258 + m_fields.size()
849 gui::IGUIImage *e = Environment->addImage(texture, pos, true,
850 data->current_parent, spec.fid, 0);
851 auto style = getDefaultStyleForElement("image", spec.fname);
852 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
853 m_fields.push_back(spec);
855 // images should let events through
857 m_clickthrough_elements.push_back(e);
860 errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl;
863 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
865 std::vector<std::string> parts = split(element, ';');
867 if (parts.size() != 6 && parts.size() != 7 &&
868 !(parts.size() > 7 && m_formspec_version > FORMSPEC_API_VERSION)) {
869 errorstream << "Invalid animated_image element(" << parts.size()
870 << "): '" << element << "'" << std::endl;
874 std::vector<std::string> v_pos = split(parts[0], ',');
875 std::vector<std::string> v_geom = split(parts[1], ',');
876 std::string name = parts[2];
877 std::string texture_name = unescape_string(parts[3]);
878 s32 frame_count = stoi(parts[4]);
879 s32 frame_duration = stoi(parts[5]);
881 MY_CHECKPOS("animated_image", 0);
882 MY_CHECKGEOM("animated_image", 1);
887 if (data->real_coordinates) {
888 pos = getRealCoordinateBasePos(v_pos);
889 geom = getRealCoordinateGeometry(v_geom);
891 pos = getElementBasePos(&v_pos);
892 geom.X = stof(v_geom[0]) * (float)imgsize.X;
893 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
896 if (!data->explicit_size)
897 warningstream << "Invalid use of animated_image without a size[] element" << std::endl;
903 258 + m_fields.size()
905 spec.ftype = f_AnimatedImage;
908 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
910 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid,
911 rect, texture_name, frame_count, frame_duration, m_tsrc);
913 if (parts.size() >= 7)
914 e->setFrameIndex(stoi(parts[6]) - 1);
916 auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
917 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
920 m_fields.push_back(spec);
923 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
925 std::vector<std::string> parts = split(element,';');
927 if ((parts.size() == 3) ||
928 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
930 std::vector<std::string> v_pos = split(parts[0],',');
931 std::vector<std::string> v_geom = split(parts[1],',');
932 std::string name = parts[2];
934 MY_CHECKPOS("itemimage",0);
935 MY_CHECKGEOM("itemimage",1);
940 if (data->real_coordinates) {
941 pos = getRealCoordinateBasePos(v_pos);
942 geom = getRealCoordinateGeometry(v_geom);
944 pos = getElementBasePos(&v_pos);
945 geom.X = stof(v_geom[0]) * (float)imgsize.X;
946 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
949 if(!data->explicit_size)
950 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
956 258 + m_fields.size(),
959 spec.ftype = f_ItemImage;
961 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
962 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
963 auto style = getDefaultStyleForElement("item_image", spec.fname);
964 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
966 // item images should let events through
967 m_clickthrough_elements.push_back(e);
969 m_fields.push_back(spec);
972 errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
975 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
976 const std::string &type)
978 std::vector<std::string> parts = split(element,';');
980 if ((parts.size() == 4) ||
981 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
983 std::vector<std::string> v_pos = split(parts[0],',');
984 std::vector<std::string> v_geom = split(parts[1],',');
985 std::string name = parts[2];
986 std::string label = parts[3];
988 MY_CHECKPOS("button",0);
989 MY_CHECKGEOM("button",1);
993 core::rect<s32> rect;
995 if (data->real_coordinates) {
996 pos = getRealCoordinateBasePos(v_pos);
997 geom = getRealCoordinateGeometry(v_geom);
998 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1001 pos = getElementBasePos(&v_pos);
1002 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1003 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1005 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
1006 pos.X + geom.X, pos.Y + m_btn_height);
1009 if(!data->explicit_size)
1010 warningstream<<"invalid use of button without a size[] element"<<std::endl;
1012 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1018 258 + m_fields.size()
1020 spec.ftype = f_Button;
1021 if(type == "button_exit")
1022 spec.is_exit = true;
1024 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1025 data->current_parent, spec.fid, spec.flabel.c_str());
1027 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1028 e->setStyles(style);
1030 if (spec.fname == data->focused_fieldname) {
1031 Environment->setFocus(e);
1034 m_fields.push_back(spec);
1037 errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl;
1040 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1042 std::vector<std::string> parts = split(element,';');
1044 if ((parts.size() >= 3 && parts.size() <= 5) ||
1045 (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
1046 std::vector<std::string> v_pos = split(parts[0],',');
1047 std::vector<std::string> v_geom = split(parts[1],',');
1048 std::string name = unescape_string(parts[2]);
1050 MY_CHECKPOS("background",0);
1051 MY_CHECKGEOM("background",1);
1056 if (data->real_coordinates) {
1057 pos = getRealCoordinateBasePos(v_pos);
1058 geom = getRealCoordinateGeometry(v_geom);
1060 pos = getElementBasePos(&v_pos);
1061 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1062 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1064 geom.X = stof(v_geom[0]) * spacing.X;
1065 geom.Y = stof(v_geom[1]) * spacing.Y;
1069 if (parts.size() >= 4 && is_yes(parts[3])) {
1070 if (data->real_coordinates) {
1071 pos = getRealCoordinateBasePos(v_pos) * -1;
1074 pos.X = stoi(v_pos[0]); //acts as offset
1075 pos.Y = stoi(v_pos[1]);
1080 core::rect<s32> middle;
1081 if (parts.size() >= 5) {
1082 std::vector<std::string> v_middle = split(parts[4], ',');
1083 if (v_middle.size() == 1) {
1084 s32 x = stoi(v_middle[0]);
1085 middle.UpperLeftCorner = core::vector2di(x, x);
1086 middle.LowerRightCorner = core::vector2di(-x, -x);
1087 } else if (v_middle.size() == 2) {
1088 s32 x = stoi(v_middle[0]);
1089 s32 y = stoi(v_middle[1]);
1090 middle.UpperLeftCorner = core::vector2di(x, y);
1091 middle.LowerRightCorner = core::vector2di(-x, -y);
1092 // `-x` is interpreted as `w - x`
1093 } else if (v_middle.size() == 4) {
1094 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1095 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1097 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1101 if (!data->explicit_size && !clip)
1102 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1108 258 + m_fields.size()
1111 core::rect<s32> rect;
1113 // no auto_clip => position like normal image
1114 rect = core::rect<s32>(pos, pos + geom);
1116 // it will be auto-clipped when drawing
1117 rect = core::rect<s32>(-pos, pos);
1120 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1121 rect, name, middle, m_tsrc, clip);
1123 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1125 e->setNotClipped(true);
1127 e->setVisible(false); // the element is drawn manually before all others
1129 m_backgrounds.push_back(e);
1130 m_fields.push_back(spec);
1133 errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl;
1136 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1138 std::vector<std::string> parts = split(element,';');
1140 data->table_options.clear();
1141 for (const std::string &part : parts) {
1142 // Parse table option
1143 std::string opt = unescape_string(part);
1144 data->table_options.push_back(GUITable::splitOption(opt));
1148 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1150 std::vector<std::string> parts = split(element,';');
1152 data->table_columns.clear();
1153 for (const std::string &part : parts) {
1154 std::vector<std::string> col_parts = split(part,',');
1155 GUITable::TableColumn column;
1156 // Parse column type
1157 if (!col_parts.empty())
1158 column.type = col_parts[0];
1159 // Parse column options
1160 for (size_t j = 1; j < col_parts.size(); ++j) {
1161 std::string opt = unescape_string(col_parts[j]);
1162 column.options.push_back(GUITable::splitOption(opt));
1164 data->table_columns.push_back(column);
1168 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1170 std::vector<std::string> parts = split(element,';');
1172 if (((parts.size() == 4) || (parts.size() == 5)) ||
1173 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1175 std::vector<std::string> v_pos = split(parts[0],',');
1176 std::vector<std::string> v_geom = split(parts[1],',');
1177 std::string name = parts[2];
1178 std::vector<std::string> items = split(parts[3],',');
1179 std::string str_initial_selection;
1180 std::string str_transparent = "false";
1182 if (parts.size() >= 5)
1183 str_initial_selection = parts[4];
1185 MY_CHECKPOS("table",0);
1186 MY_CHECKGEOM("table",1);
1191 if (data->real_coordinates) {
1192 pos = getRealCoordinateBasePos(v_pos);
1193 geom = getRealCoordinateGeometry(v_geom);
1195 pos = getElementBasePos(&v_pos);
1196 geom.X = stof(v_geom[0]) * spacing.X;
1197 geom.Y = stof(v_geom[1]) * spacing.Y;
1200 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1206 258 + m_fields.size()
1209 spec.ftype = f_Table;
1211 for (std::string &item : items) {
1212 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1215 //now really show table
1216 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1219 if (spec.fname == data->focused_fieldname) {
1220 Environment->setFocus(e);
1223 e->setTable(data->table_options, data->table_columns, items);
1225 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1226 e->setDynamicData(data->table_dyndata[name]);
1229 if (!str_initial_selection.empty() && str_initial_selection != "0")
1230 e->setSelected(stoi(str_initial_selection));
1232 auto style = getDefaultStyleForElement("table", name);
1233 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1235 m_tables.emplace_back(spec, e);
1236 m_fields.push_back(spec);
1239 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1242 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1244 std::vector<std::string> parts = split(element,';');
1246 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1247 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1249 std::vector<std::string> v_pos = split(parts[0],',');
1250 std::vector<std::string> v_geom = split(parts[1],',');
1251 std::string name = parts[2];
1252 std::vector<std::string> items = split(parts[3],',');
1253 std::string str_initial_selection;
1254 std::string str_transparent = "false";
1256 if (parts.size() >= 5)
1257 str_initial_selection = parts[4];
1259 if (parts.size() >= 6)
1260 str_transparent = parts[5];
1262 MY_CHECKPOS("textlist",0);
1263 MY_CHECKGEOM("textlist",1);
1268 if (data->real_coordinates) {
1269 pos = getRealCoordinateBasePos(v_pos);
1270 geom = getRealCoordinateGeometry(v_geom);
1272 pos = getElementBasePos(&v_pos);
1273 geom.X = stof(v_geom[0]) * spacing.X;
1274 geom.Y = stof(v_geom[1]) * spacing.Y;
1277 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1283 258 + m_fields.size()
1286 spec.ftype = f_Table;
1288 for (std::string &item : items) {
1289 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1292 //now really show list
1293 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1296 if (spec.fname == data->focused_fieldname) {
1297 Environment->setFocus(e);
1300 e->setTextList(items, is_yes(str_transparent));
1302 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1303 e->setDynamicData(data->table_dyndata[name]);
1306 if (!str_initial_selection.empty() && str_initial_selection != "0")
1307 e->setSelected(stoi(str_initial_selection));
1309 auto style = getDefaultStyleForElement("textlist", name);
1310 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1312 m_tables.emplace_back(spec, e);
1313 m_fields.push_back(spec);
1316 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1320 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1322 std::vector<std::string> parts = split(element,';');
1324 if ((parts.size() == 5) ||
1325 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1327 std::vector<std::string> v_pos = split(parts[0],',');
1328 std::string name = parts[2];
1329 std::vector<std::string> items = split(parts[3],',');
1330 std::string str_initial_selection;
1331 str_initial_selection = parts[4];
1333 MY_CHECKPOS("dropdown",0);
1337 core::rect<s32> rect;
1339 if (data->real_coordinates) {
1340 std::vector<std::string> v_geom = split(parts[1],',');
1342 if (v_geom.size() == 1)
1343 v_geom.emplace_back("1");
1345 MY_CHECKGEOM("dropdown",1);
1347 pos = getRealCoordinateBasePos(v_pos);
1348 geom = getRealCoordinateGeometry(v_geom);
1349 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1351 pos = getElementBasePos(&v_pos);
1353 s32 width = stof(parts[1]) * spacing.Y;
1355 rect = core::rect<s32>(pos.X, pos.Y,
1356 pos.X + width, pos.Y + (m_btn_height * 2));
1363 258 + m_fields.size()
1366 spec.ftype = f_DropDown;
1369 //now really show list
1370 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1373 if (spec.fname == data->focused_fieldname) {
1374 Environment->setFocus(e);
1377 for (const std::string &item : items) {
1378 e->addItem(unescape_translate(unescape_string(
1379 utf8_to_wide(item))).c_str());
1382 if (!str_initial_selection.empty())
1383 e->setSelected(stoi(str_initial_selection)-1);
1385 auto style = getDefaultStyleForElement("dropdown", name);
1386 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1388 m_fields.push_back(spec);
1390 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1391 std::vector<std::string> &values = m_dropdowns.back().second;
1392 for (const std::string &item : items) {
1393 values.push_back(unescape_string(item));
1398 errorstream << "Invalid dropdown element(" << parts.size() << "): '"
1399 << element << "'" << std::endl;
1402 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1404 std::vector<std::string> parts = split(element,';');
1405 if (parts.size() == 2 ||
1406 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1407 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1411 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1413 std::vector<std::string> parts = split(element,';');
1415 if ((parts.size() == 4) ||
1416 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
1418 std::vector<std::string> v_pos = split(parts[0],',');
1419 std::vector<std::string> v_geom = split(parts[1],',');
1420 std::string name = parts[2];
1421 std::string label = parts[3];
1423 MY_CHECKPOS("pwdfield",0);
1424 MY_CHECKGEOM("pwdfield",1);
1429 if (data->real_coordinates) {
1430 pos = getRealCoordinateBasePos(v_pos);
1431 geom = getRealCoordinateGeometry(v_geom);
1433 pos = getElementBasePos(&v_pos);
1436 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1438 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1439 pos.Y -= m_btn_height;
1440 geom.Y = m_btn_height*2;
1443 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1445 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1451 258 + m_fields.size(),
1457 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1458 data->current_parent, spec.fid);
1460 if (spec.fname == data->focused_fieldname) {
1461 Environment->setFocus(e);
1464 if (label.length() >= 1) {
1465 int font_height = g_fontengine->getTextHeight();
1466 rect.UpperLeftCorner.Y -= font_height;
1467 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1468 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1469 data->current_parent, 0);
1472 e->setPasswordBox(true,L'*');
1474 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1475 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1476 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1477 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1480 evt.EventType = EET_KEY_INPUT_EVENT;
1481 evt.KeyInput.Key = KEY_END;
1482 evt.KeyInput.Char = 0;
1483 evt.KeyInput.Control = false;
1484 evt.KeyInput.Shift = false;
1485 evt.KeyInput.PressedDown = true;
1488 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1489 // warning referring to field_close_on_enter[]!
1491 m_fields.push_back(spec);
1494 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1497 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1498 core::rect<s32> &rect, bool is_multiline)
1500 bool is_editable = !spec.fname.empty();
1501 if (!is_editable && !is_multiline) {
1502 // spec field id to 0, this stops submit searching for a value that isn't there
1503 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1504 data->current_parent, 0);
1510 } else if (is_multiline &&
1511 spec.fdefault.empty() && !spec.flabel.empty()) {
1512 // Multiline textareas: swap default and label for backwards compat
1513 spec.flabel.swap(spec.fdefault);
1516 gui::IGUIEditBox *e = nullptr;
1517 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1518 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1520 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1521 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1522 data->current_parent, spec.fid, rect, is_editable, is_multiline);
1525 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1526 data->current_parent, spec.fid, rect, is_editable, true);
1527 } else if (is_editable) {
1528 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1529 data->current_parent, spec.fid);
1534 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1537 if (is_editable && spec.fname == data->focused_fieldname)
1538 Environment->setFocus(e);
1541 e->setMultiLine(true);
1542 e->setWordWrap(true);
1543 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1546 evt.EventType = EET_KEY_INPUT_EVENT;
1547 evt.KeyInput.Key = KEY_END;
1548 evt.KeyInput.Char = 0;
1549 evt.KeyInput.Control = 0;
1550 evt.KeyInput.Shift = 0;
1551 evt.KeyInput.PressedDown = true;
1555 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1556 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1557 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1558 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1559 e->setDrawBackground(false);
1565 if (!spec.flabel.empty()) {
1566 int font_height = g_fontengine->getTextHeight();
1567 rect.UpperLeftCorner.Y -= font_height;
1568 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1569 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1570 rect, false, true, data->current_parent, 0);
1573 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1577 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1578 std::vector<std::string> &parts)
1580 std::string name = parts[0];
1581 std::string label = parts[1];
1582 std::string default_val = parts[2];
1584 core::rect<s32> rect;
1586 if (data->explicit_size)
1587 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1589 v2s32 pos = getElementBasePos(nullptr);
1590 pos.Y = (data->simple_field_count + 2) * 60;
1591 v2s32 size = DesiredRect.getSize();
1593 rect = core::rect<s32>(
1594 size.X / 2 - 150, pos.Y,
1595 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1600 default_val = m_form_src->resolveText(default_val);
1603 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1608 utf8_to_wide(unescape_string(default_val)),
1609 258 + m_fields.size(),
1614 createTextField(data, spec, rect, false);
1616 m_fields.push_back(spec);
1618 data->simple_field_count++;
1621 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1622 const std::string &type)
1624 std::vector<std::string> v_pos = split(parts[0],',');
1625 std::vector<std::string> v_geom = split(parts[1],',');
1626 std::string name = parts[2];
1627 std::string label = parts[3];
1628 std::string default_val = parts[4];
1630 MY_CHECKPOS(type,0);
1631 MY_CHECKGEOM(type,1);
1636 if (data->real_coordinates) {
1637 pos = getRealCoordinateBasePos(v_pos);
1638 geom = getRealCoordinateGeometry(v_geom);
1640 pos = getElementBasePos(&v_pos);
1643 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1645 if (type == "textarea")
1647 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1648 pos.Y += m_btn_height;
1652 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1653 pos.Y -= m_btn_height;
1654 geom.Y = m_btn_height*2;
1658 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1660 if(!data->explicit_size)
1661 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1664 default_val = m_form_src->resolveText(default_val);
1667 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1672 utf8_to_wide(unescape_string(default_val)),
1673 258 + m_fields.size(),
1678 createTextField(data, spec, rect, type == "textarea");
1680 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1681 // warning referring to field_close_on_enter[]!
1683 m_fields.push_back(spec);
1686 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1687 const std::string &type)
1689 std::vector<std::string> parts = split(element,';');
1691 if (parts.size() == 3 || parts.size() == 4) {
1692 parseSimpleField(data,parts);
1696 if ((parts.size() == 5) ||
1697 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1699 parseTextArea(data,parts,type);
1702 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1705 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1707 std::vector<std::string> parts = split(element, ';');
1709 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1710 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1714 std::vector<std::string> v_pos = split(parts[0], ',');
1715 std::vector<std::string> v_geom = split(parts[1], ',');
1716 std::string name = parts[2];
1717 std::string text = parts[3];
1719 MY_CHECKPOS("hypertext", 0);
1720 MY_CHECKGEOM("hypertext", 1);
1725 if (data->real_coordinates) {
1726 pos = getRealCoordinateBasePos(v_pos);
1727 geom = getRealCoordinateGeometry(v_geom);
1729 pos = getElementBasePos(&v_pos);
1732 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1733 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1734 pos.Y += m_btn_height;
1737 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1740 text = m_form_src->resolveText(text);
1744 utf8_to_wide(unescape_string(text)),
1746 258 + m_fields.size()
1749 spec.ftype = f_HyperText;
1750 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1751 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1754 m_fields.push_back(spec);
1757 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1759 std::vector<std::string> parts = split(element,';');
1761 if ((parts.size() == 2) ||
1762 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1764 std::vector<std::string> v_pos = split(parts[0],',');
1765 std::string text = parts[1];
1767 MY_CHECKPOS("label",0);
1769 if(!data->explicit_size)
1770 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1772 std::vector<std::string> lines = split(text, '\n');
1774 for (unsigned int i = 0; i != lines.size(); i++) {
1775 std::wstring wlabel_colors = translate_string(
1776 utf8_to_wide(unescape_string(lines[i])));
1777 // Without color escapes to get the font dimensions
1778 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1780 core::rect<s32> rect;
1782 if (data->real_coordinates) {
1783 // Lines are spaced at the distance of 1/2 imgsize.
1784 // This alows lines that line up with the new elements
1785 // easily without sacrificing good line distance. If
1786 // it was one whole imgsize, it would have too much
1788 v2s32 pos = getRealCoordinateBasePos(v_pos);
1790 // Labels are positioned by their center, not their top.
1791 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1793 rect = core::rect<s32>(
1795 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1799 // Lines are spaced at the nominal distance of
1800 // 2/5 inventory slot, even if the font doesn't
1801 // quite match that. This provides consistent
1802 // form layout, at the expense of sometimes
1803 // having sub-optimal spacing for the font.
1804 // We multiply by 2 and then divide by 5, rather
1805 // than multiply by 0.4, to get exact results
1806 // in the integer cases: 0.4 is not exactly
1807 // representable in binary floating point.
1809 v2s32 pos = getElementBasePos(nullptr);
1810 pos.X += stof(v_pos[0]) * spacing.X;
1811 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1813 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1815 rect = core::rect<s32>(
1816 pos.X, pos.Y - m_btn_height,
1817 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1818 pos.Y + m_btn_height);
1825 258 + m_fields.size(),
1828 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1829 spec.flabel.c_str(), rect, false, false, data->current_parent,
1831 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1833 auto style = getDefaultStyleForElement("label", spec.fname);
1834 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1835 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1837 m_fields.push_back(spec);
1839 // labels should let events through
1841 m_clickthrough_elements.push_back(e);
1846 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1847 << "'" << std::endl;
1850 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1852 std::vector<std::string> parts = split(element,';');
1854 if ((parts.size() == 2) ||
1855 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1857 std::vector<std::string> v_pos = split(parts[0],',');
1858 std::wstring text = unescape_translate(
1859 unescape_string(utf8_to_wide(parts[1])));
1861 MY_CHECKPOS("vertlabel",1);
1864 core::rect<s32> rect;
1866 if (data->real_coordinates) {
1867 pos = getRealCoordinateBasePos(v_pos);
1869 // Vertlabels are positioned by center, not left.
1870 pos.X -= imgsize.X / 2;
1872 // We use text.length + 1 because without it, the rect
1873 // isn't quite tall enough and cuts off the text.
1874 rect = core::rect<s32>(pos.X, pos.Y,
1876 pos.Y + font_line_height(m_font) *
1877 (text.length() + 1));
1880 pos = getElementBasePos(&v_pos);
1882 // As above, the length must be one longer. The width of
1883 // the rect (15 pixels) seems rather arbitrary, but
1884 // changing it might break something.
1885 rect = core::rect<s32>(
1886 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1888 font_line_height(m_font) *
1889 (text.length() + 1) +
1890 ((imgsize.Y/2) - m_btn_height));
1893 if(!data->explicit_size)
1894 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1898 for (wchar_t i : text) {
1907 258 + m_fields.size()
1909 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1910 rect, false, false, data->current_parent, spec.fid);
1911 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1913 auto style = getDefaultStyleForElement("vertlabel", spec.fname, "label");
1914 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1915 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1917 m_fields.push_back(spec);
1919 // vertlabels should let events through
1921 m_clickthrough_elements.push_back(e);
1924 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1927 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1928 const std::string &type)
1930 std::vector<std::string> parts = split(element,';');
1932 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1933 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1935 std::vector<std::string> v_pos = split(parts[0],',');
1936 std::vector<std::string> v_geom = split(parts[1],',');
1937 std::string image_name = parts[2];
1938 std::string name = parts[3];
1939 std::string label = parts[4];
1941 MY_CHECKPOS("imagebutton",0);
1942 MY_CHECKGEOM("imagebutton",1);
1944 std::string pressed_image_name;
1946 if (parts.size() >= 8) {
1947 pressed_image_name = parts[7];
1953 if (data->real_coordinates) {
1954 pos = getRealCoordinateBasePos(v_pos);
1955 geom = getRealCoordinateGeometry(v_geom);
1957 pos = getElementBasePos(&v_pos);
1958 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1959 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1962 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1965 if (!data->explicit_size)
1966 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1968 image_name = unescape_string(image_name);
1969 pressed_image_name = unescape_string(pressed_image_name);
1971 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1976 utf8_to_wide(image_name),
1977 258 + m_fields.size()
1979 spec.ftype = f_Button;
1980 if (type == "image_button_exit")
1981 spec.is_exit = true;
1983 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1984 data->current_parent, spec.fid, spec.flabel.c_str());
1986 if (spec.fname == data->focused_fieldname) {
1987 Environment->setFocus(e);
1990 auto style = getStyleForElement("image_button", spec.fname);
1992 // Override style properties with values specified directly in the element
1993 if (!image_name.empty())
1994 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1996 if (!pressed_image_name.empty())
1997 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
1999 if (parts.size() >= 7) {
2000 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
2001 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
2004 e->setStyles(style);
2005 e->setScaleImage(true);
2007 m_fields.push_back(spec);
2011 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2014 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2016 std::vector<std::string> parts = split(element, ';');
2018 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
2019 data->real_coordinates) || ((parts.size() > 6) &&
2020 (m_formspec_version > FORMSPEC_API_VERSION)))
2022 std::vector<std::string> v_pos = split(parts[0],',');
2024 // If we're using real coordinates, add an extra field for height.
2025 // Width is not here because tabs are the width of the text, and
2026 // there's no reason to change that.
2028 std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
2029 bool auto_width = true;
2030 if (parts.size() == 7) {
2033 v_geom = split(parts[1], ',');
2034 if (v_geom.size() == 1)
2035 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2040 std::string name = parts[i+1];
2041 std::vector<std::string> buttons = split(parts[i+2], ',');
2042 std::string str_index = parts[i+3];
2043 bool show_background = true;
2044 bool show_border = true;
2045 int tab_index = stoi(str_index) - 1;
2047 MY_CHECKPOS("tabheader", 0);
2049 if (parts.size() == 6 + i) {
2050 if (parts[4+i] == "true")
2051 show_background = false;
2052 if (parts[5+i] == "false")
2053 show_border = false;
2060 258 + m_fields.size()
2063 spec.ftype = f_TabHeader;
2068 if (data->real_coordinates) {
2069 pos = getRealCoordinateBasePos(v_pos);
2071 geom = getRealCoordinateGeometry(v_geom);
2072 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2074 geom.X = DesiredRect.getWidth(); // Set automatic width
2076 MY_CHECKGEOM("tabheader", 1);
2078 v2f32 pos_f = pos_offset * spacing;
2079 pos_f.X += stof(v_pos[0]) * spacing.X;
2080 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2081 pos = v2s32(pos_f.X, pos_f.Y);
2083 geom.Y = m_btn_height * 2;
2084 geom.X = DesiredRect.getWidth();
2087 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2090 gui::IGUITabControl *e = Environment->addTabControl(rect,
2091 data->current_parent, show_background, show_border, spec.fid);
2092 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2093 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2094 e->setTabHeight(geom.Y);
2096 if (spec.fname == data->focused_fieldname) {
2097 Environment->setFocus(e);
2100 auto style = getDefaultStyleForElement("tabheader", name);
2101 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2103 for (const std::string &button : buttons) {
2104 auto tab = e->addTab(unescape_translate(unescape_string(
2105 utf8_to_wide(button))).c_str(), -1);
2106 if (style.isNotDefault(StyleSpec::BGCOLOR))
2107 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2109 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2112 if ((tab_index >= 0) &&
2113 (buttons.size() < INT_MAX) &&
2114 (tab_index < (int) buttons.size()))
2115 e->setActiveTab(tab_index);
2117 m_fields.push_back(spec);
2120 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2121 << element << "'" << std::endl;
2124 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2126 if (m_client == 0) {
2127 warningstream << "invalid use of item_image_button with m_client==0"
2132 std::vector<std::string> parts = split(element,';');
2134 if ((parts.size() == 5) ||
2135 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2137 std::vector<std::string> v_pos = split(parts[0],',');
2138 std::vector<std::string> v_geom = split(parts[1],',');
2139 std::string item_name = parts[2];
2140 std::string name = parts[3];
2141 std::string label = parts[4];
2143 label = unescape_string(label);
2144 item_name = unescape_string(item_name);
2146 MY_CHECKPOS("itemimagebutton",0);
2147 MY_CHECKGEOM("itemimagebutton",1);
2152 if (data->real_coordinates) {
2153 pos = getRealCoordinateBasePos(v_pos);
2154 geom = getRealCoordinateGeometry(v_geom);
2156 pos = getElementBasePos(&v_pos);
2157 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2158 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2161 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2163 if(!data->explicit_size)
2164 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2166 IItemDefManager *idef = m_client->idef();
2168 item.deSerialize(item_name, idef);
2171 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2172 m_default_tooltip_bgcolor,
2173 m_default_tooltip_color);
2175 // the spec for the button
2178 utf8_to_wide(label),
2179 utf8_to_wide(item_name),
2180 258 + m_fields.size(),
2184 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2185 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2186 item_name, m_client);
2188 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2189 e_btn->setStyles(style);
2191 if (spec_btn.fname == data->focused_fieldname) {
2192 Environment->setFocus(e_btn);
2195 spec_btn.ftype = f_Button;
2196 rect += data->basepos-padding;
2197 spec_btn.rect = rect;
2198 m_fields.push_back(spec_btn);
2201 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2204 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2206 std::vector<std::string> parts = split(element,';');
2208 if ((parts.size() == 3) ||
2209 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2211 std::vector<std::string> v_pos = split(parts[0],',');
2212 std::vector<std::string> v_geom = split(parts[1],',');
2214 MY_CHECKPOS("box",0);
2215 MY_CHECKGEOM("box",1);
2220 if (data->real_coordinates) {
2221 pos = getRealCoordinateBasePos(v_pos);
2222 geom = getRealCoordinateGeometry(v_geom);
2224 pos = getElementBasePos(&v_pos);
2225 geom.X = stof(v_geom[0]) * spacing.X;
2226 geom.Y = stof(v_geom[1]) * spacing.Y;
2229 video::SColor tmp_color;
2231 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2236 258 + m_fields.size(),
2241 core::rect<s32> rect(pos, pos + geom);
2243 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid,
2246 auto style = getDefaultStyleForElement("box", spec.fname);
2247 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2251 m_fields.push_back(spec);
2254 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2258 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2261 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2263 std::vector<std::string> parts = split(element,';');
2264 const u32 parameter_count = parts.size();
2266 if ((parameter_count > 2 && m_formspec_version < 3) ||
2267 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2268 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2269 << element << "'" << std::endl;
2274 if (parameter_count >= 1 && parts[0] != "")
2275 parseColorString(parts[0], m_bgcolor, false);
2278 if (parameter_count >= 2) {
2279 if (parts[1] == "both") {
2280 m_bgnonfullscreen = true;
2281 m_bgfullscreen = true;
2282 } else if (parts[1] == "neither") {
2283 m_bgnonfullscreen = false;
2284 m_bgfullscreen = false;
2285 } else if (parts[1] != "" || m_formspec_version < 3) {
2286 m_bgfullscreen = is_yes(parts[1]);
2287 m_bgnonfullscreen = !m_bgfullscreen;
2292 if (parameter_count >= 3 && parts[2] != "")
2293 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2296 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2298 std::vector<std::string> parts = split(element,';');
2300 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2301 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2303 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2304 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2306 if (parts.size() >= 3) {
2307 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2309 data->inventorylist_options.slotborder = true;
2312 if (parts.size() == 5) {
2313 video::SColor tmp_color;
2315 if (parseColorString(parts[3], tmp_color, false))
2316 m_default_tooltip_bgcolor = tmp_color;
2317 if (parseColorString(parts[4], tmp_color, false))
2318 m_default_tooltip_color = tmp_color;
2321 // update all already parsed inventorylists
2322 for (GUIInventoryList *e : m_inventorylists) {
2323 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2324 data->inventorylist_options.slotbg_h);
2325 e->setSlotBorders(data->inventorylist_options.slotborder,
2326 data->inventorylist_options.slotbordercolor);
2330 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2333 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2335 std::vector<std::string> parts = split(element,';');
2336 if (parts.size() < 2) {
2337 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2338 << element << "'" << std::endl;
2342 // Get mode and check size
2343 bool rect_mode = parts[0].find(',') != std::string::npos;
2344 size_t base_size = rect_mode ? 3 : 2;
2345 if (parts.size() != base_size && parts.size() != base_size + 2) {
2346 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2347 << element << "'" << std::endl;
2352 video::SColor bgcolor = m_default_tooltip_bgcolor;
2353 video::SColor color = m_default_tooltip_color;
2354 if (parts.size() == base_size + 2 &&
2355 (!parseColorString(parts[base_size], bgcolor, false) ||
2356 !parseColorString(parts[base_size + 1], color, false))) {
2357 errorstream << "Invalid color in tooltip element(" << parts.size()
2358 << "): '" << element << "'" << std::endl;
2362 // Make tooltip spec
2363 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2364 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2368 std::vector<std::string> v_pos = split(parts[0], ',');
2369 std::vector<std::string> v_geom = split(parts[1], ',');
2371 MY_CHECKPOS("tooltip", 0);
2372 MY_CHECKGEOM("tooltip", 1);
2377 if (data->real_coordinates) {
2378 pos = getRealCoordinateBasePos(v_pos);
2379 geom = getRealCoordinateGeometry(v_geom);
2381 pos = getElementBasePos(&v_pos);
2382 geom.X = stof(v_geom[0]) * spacing.X;
2383 geom.Y = stof(v_geom[1]) * spacing.Y;
2386 FieldSpec fieldspec(
2390 258 + m_fields.size()
2393 core::rect<s32> rect(pos, pos + geom);
2395 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2396 data->current_parent, fieldspec.fid, rect);
2398 // the element the rect tooltip is bound to should not block mouse-clicks
2399 e->setVisible(false);
2401 m_fields.push_back(fieldspec);
2402 m_tooltip_rects.emplace_back(e, spec);
2405 m_tooltips[parts[0]] = spec;
2409 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2415 std::vector<std::string> parts = split(data,'[');
2417 if (parts.size() < 2) {
2421 if (trim(parts[0]) != "formspec_version") {
2425 if (is_number(parts[1])) {
2426 m_formspec_version = mystoi(parts[1]);
2433 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2435 if (element.empty())
2438 std::vector<std::string> parts = split(element,'[');
2440 if (parts.size() < 2)
2443 std::string type = trim(parts[0]);
2444 std::string description = trim(parts[1]);
2446 if (type != "size" && type != "invsize")
2449 if (type == "invsize")
2450 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2452 parseSize(data, description);
2457 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2459 if (element.empty())
2462 std::vector<std::string> parts = split(element, '[');
2464 if (parts.size() != 2)
2467 std::string type = trim(parts[0]);
2468 std::string description = trim(parts[1]);
2470 if (type != "position")
2473 parsePosition(data, description);
2478 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2480 std::vector<std::string> parts = split(element, ',');
2482 if (parts.size() == 2) {
2483 data->offset.X = stof(parts[0]);
2484 data->offset.Y = stof(parts[1]);
2488 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2491 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2493 if (element.empty())
2496 std::vector<std::string> parts = split(element, '[');
2498 if (parts.size() != 2)
2501 std::string type = trim(parts[0]);
2502 std::string description = trim(parts[1]);
2504 if (type != "anchor")
2507 parseAnchor(data, description);
2512 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2514 std::vector<std::string> parts = split(element, ',');
2516 if (parts.size() == 2) {
2517 data->anchor.X = stof(parts[0]);
2518 data->anchor.Y = stof(parts[1]);
2522 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2523 << "'" << std::endl;
2526 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2528 std::vector<std::string> parts = split(element, ';');
2530 if (parts.size() < 2) {
2531 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2532 << "'" << std::endl;
2539 for (size_t i = 1; i < parts.size(); i++) {
2540 size_t equal_pos = parts[i].find('=');
2541 if (equal_pos == std::string::npos) {
2542 errorstream << "Invalid style element (Property missing value): '" << element
2543 << "'" << std::endl;
2547 std::string propname = trim(parts[i].substr(0, equal_pos));
2548 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2550 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2552 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2553 if (prop == StyleSpec::NONE) {
2554 if (property_warned.find(propname) != property_warned.end()) {
2555 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2557 << "'" << std::endl;
2558 property_warned.insert(propname);
2563 spec.set(prop, value);
2566 std::vector<std::string> selectors = split(parts[0], ',');
2567 for (size_t sel = 0; sel < selectors.size(); sel++) {
2568 std::string selector = trim(selectors[sel]);
2570 // Copy the style properties to a new StyleSpec
2571 // This allows a separate state mask per-selector
2572 StyleSpec selector_spec = spec;
2574 // Parse state information, if it exists
2575 bool state_valid = true;
2576 size_t state_pos = selector.find(':');
2577 if (state_pos != std::string::npos) {
2578 std::string state_str = selector.substr(state_pos + 1);
2579 selector = selector.substr(0, state_pos);
2581 if (state_str.empty()) {
2582 errorstream << "Invalid style element (Invalid state): '" << element
2583 << "'" << std::endl;
2584 state_valid = false;
2586 std::vector<std::string> states = split(state_str, '+');
2587 for (std::string &state : states) {
2588 StyleSpec::State converted = StyleSpec::getStateByName(state);
2589 if (converted == StyleSpec::STATE_INVALID) {
2590 infostream << "Unknown style state " << state <<
2591 " in element '" << element << "'" << std::endl;
2592 state_valid = false;
2596 selector_spec.addState(converted);
2602 // Skip this selector
2607 theme_by_type[selector].push_back(selector_spec);
2609 theme_by_name[selector].push_back(selector_spec);
2612 // Backwards-compatibility for existing _hovered/_pressed properties
2613 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2614 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2615 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2616 StyleSpec hover_spec;
2617 hover_spec.addState(StyleSpec::STATE_HOVERED);
2619 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2620 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2622 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2623 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2625 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2626 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2630 theme_by_type[selector].push_back(hover_spec);
2632 theme_by_name[selector].push_back(hover_spec);
2635 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2636 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2637 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2638 StyleSpec press_spec;
2639 press_spec.addState(StyleSpec::STATE_PRESSED);
2641 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2642 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2644 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2645 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2647 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2648 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2652 theme_by_type[selector].push_back(press_spec);
2654 theme_by_name[selector].push_back(press_spec);
2662 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2665 if (element.empty())
2668 if (parseVersionDirect(element))
2671 std::vector<std::string> parts = split(element,'[');
2673 // ugly workaround to keep compatibility
2674 if (parts.size() > 2) {
2675 if (trim(parts[0]) == "image") {
2676 for (unsigned int i=2;i< parts.size(); i++) {
2677 parts[1] += "[" + parts[i];
2683 if (parts.size() < 2) {
2687 std::string type = trim(parts[0]);
2688 std::string description = trim(parts[1]);
2690 if (type == "container") {
2691 parseContainer(data, description);
2695 if (type == "container_end") {
2696 parseContainerEnd(data);
2700 if (type == "list") {
2701 parseList(data, description);
2705 if (type == "listring") {
2706 parseListRing(data, description);
2710 if (type == "checkbox") {
2711 parseCheckbox(data, description);
2715 if (type == "image") {
2716 parseImage(data, description);
2720 if (type == "animated_image") {
2721 parseAnimatedImage(data, description);
2725 if (type == "item_image") {
2726 parseItemImage(data, description);
2730 if (type == "button" || type == "button_exit") {
2731 parseButton(data, description, type);
2735 if (type == "background" || type == "background9") {
2736 parseBackground(data, description);
2740 if (type == "tableoptions"){
2741 parseTableOptions(data,description);
2745 if (type == "tablecolumns"){
2746 parseTableColumns(data,description);
2750 if (type == "table"){
2751 parseTable(data,description);
2755 if (type == "textlist"){
2756 parseTextList(data,description);
2760 if (type == "dropdown"){
2761 parseDropDown(data,description);
2765 if (type == "field_close_on_enter") {
2766 parseFieldCloseOnEnter(data, description);
2770 if (type == "pwdfield") {
2771 parsePwdField(data,description);
2775 if ((type == "field") || (type == "textarea")){
2776 parseField(data,description,type);
2780 if (type == "hypertext") {
2781 parseHyperText(data,description);
2785 if (type == "label") {
2786 parseLabel(data,description);
2790 if (type == "vertlabel") {
2791 parseVertLabel(data,description);
2795 if (type == "item_image_button") {
2796 parseItemImageButton(data,description);
2800 if ((type == "image_button") || (type == "image_button_exit")) {
2801 parseImageButton(data,description,type);
2805 if (type == "tabheader") {
2806 parseTabHeader(data,description);
2810 if (type == "box") {
2811 parseBox(data,description);
2815 if (type == "bgcolor") {
2816 parseBackgroundColor(data,description);
2820 if (type == "listcolors") {
2821 parseListColors(data,description);
2825 if (type == "tooltip") {
2826 parseTooltip(data,description);
2830 if (type == "scrollbar") {
2831 parseScrollBar(data, description);
2835 if (type == "real_coordinates") {
2836 data->real_coordinates = is_yes(description);
2840 if (type == "style") {
2841 parseStyle(data, description, false);
2845 if (type == "style_type") {
2846 parseStyle(data, description, true);
2850 if (type == "scrollbaroptions") {
2851 parseScrollBarOptions(data, description);
2855 if (type == "scroll_container") {
2856 parseScrollContainer(data, description);
2860 if (type == "scroll_container_end") {
2861 parseScrollContainerEnd(data);
2866 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2870 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2872 /* useless to regenerate without a screensize */
2873 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2880 for (auto &m_table : m_tables) {
2881 std::string tablename = m_table.first.fname;
2882 GUITable *table = m_table.second;
2883 mydata.table_dyndata[tablename] = table->getDynamicData();
2887 if (!m_focused_element.empty())
2888 mydata.focused_fieldname = m_focused_element;
2891 gui::IGUIElement *focused_element = Environment->getFocus();
2892 if (focused_element && focused_element->getParent() == this) {
2893 s32 focused_id = focused_element->getID();
2894 if (focused_id > 257) {
2895 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2896 if (field.fid == focused_id) {
2897 mydata.focused_fieldname = field.fname;
2907 for (auto &table_it : m_tables)
2908 table_it.second->drop();
2909 for (auto &inventorylist_it : m_inventorylists)
2910 inventorylist_it->drop();
2911 for (auto &checkbox_it : m_checkboxes)
2912 checkbox_it.second->drop();
2913 for (auto &scrollbar_it : m_scrollbars)
2914 scrollbar_it.second->drop();
2915 for (auto &background_it : m_backgrounds)
2916 background_it->drop();
2917 for (auto &tooltip_rect_it : m_tooltip_rects)
2918 tooltip_rect_it.first->drop();
2919 for (auto &clickthrough_it : m_clickthrough_elements)
2920 clickthrough_it->drop();
2921 for (auto &scroll_container_it : m_scroll_containers)
2922 scroll_container_it.second->drop();
2924 mydata.size = v2s32(100, 100);
2925 mydata.screensize = screensize;
2926 mydata.offset = v2f32(0.5f, 0.5f);
2927 mydata.anchor = v2f32(0.5f, 0.5f);
2928 mydata.simple_field_count = 0;
2930 // Base position of contents of form
2931 mydata.basepos = getBasePos();
2933 // the parent for the parsed elements
2934 mydata.current_parent = this;
2936 m_inventorylists.clear();
2937 m_backgrounds.clear();
2939 m_checkboxes.clear();
2940 m_scrollbars.clear();
2943 m_tooltip_rects.clear();
2944 m_inventory_rings.clear();
2945 m_dropdowns.clear();
2946 m_scroll_containers.clear();
2947 theme_by_name.clear();
2948 theme_by_type.clear();
2949 m_clickthrough_elements.clear();
2951 m_bgnonfullscreen = true;
2952 m_bgfullscreen = false;
2954 m_formspec_version = 1;
2957 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2958 m_bgcolor = video::SColor(
2959 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2960 clamp_u8(myround(formspec_bgcolor.X)),
2961 clamp_u8(myround(formspec_bgcolor.Y)),
2962 clamp_u8(myround(formspec_bgcolor.Z))
2967 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2968 m_fullscreen_bgcolor = video::SColor(
2969 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2970 clamp_u8(myround(formspec_bgcolor.X)),
2971 clamp_u8(myround(formspec_bgcolor.Y)),
2972 clamp_u8(myround(formspec_bgcolor.Z))
2976 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2977 m_default_tooltip_color = video::SColor(255,255,255,255);
2981 assert(!m_tooltip_element);
2982 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2983 m_tooltip_element = gui::StaticText::add(Environment, L"",
2984 core::rect<s32>(0, 0, 110, 18));
2985 m_tooltip_element->enableOverrideColor(true);
2986 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2987 m_tooltip_element->setDrawBackground(true);
2988 m_tooltip_element->setDrawBorder(true);
2989 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2990 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2991 m_tooltip_element->setWordWrap(false);
2992 //we're not parent so no autograb for this one!
2993 m_tooltip_element->grab();
2996 std::vector<std::string> elements = split(m_formspec_string,']');
2999 /* try to read version from first element only */
3000 if (!elements.empty()) {
3001 if (parseVersionDirect(elements[0])) {
3006 /* we need size first in order to calculate image scale */
3007 mydata.explicit_size = false;
3008 for (; i< elements.size(); i++) {
3009 if (!parseSizeDirect(&mydata, elements[i])) {
3014 /* "position" element is always after "size" element if it used */
3015 for (; i< elements.size(); i++) {
3016 if (!parsePositionDirect(&mydata, elements[i])) {
3021 /* "anchor" element is always after "position" (or "size" element) if it used */
3022 for (; i< elements.size(); i++) {
3023 if (!parseAnchorDirect(&mydata, elements[i])) {
3028 /* "no_prepend" element is always after "position" (or "size" element) if it used */
3029 bool enable_prepends = true;
3030 for (; i < elements.size(); i++) {
3031 if (elements[i].empty())
3034 std::vector<std::string> parts = split(elements[i], '[');
3035 if (trim(parts[0]) == "no_prepend")
3036 enable_prepends = false;
3041 /* Copy of the "real_coordinates" element for after the form size. */
3042 mydata.real_coordinates = m_formspec_version >= 2;
3043 for (; i < elements.size(); i++) {
3044 std::vector<std::string> parts = split(elements[i], '[');
3045 std::string name = trim(parts[0]);
3046 if (name != "real_coordinates" || parts.size() != 2)
3047 break; // Invalid format
3049 mydata.real_coordinates = is_yes(trim(parts[1]));
3052 if (mydata.explicit_size) {
3053 // compute scaling for specified form size
3055 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3056 v2u32 delta = current_screensize - m_lockscreensize;
3058 if (current_screensize.Y > m_lockscreensize.Y)
3063 if (current_screensize.X > m_lockscreensize.X)
3068 offset = v2s32(delta.X,delta.Y);
3070 mydata.screensize = m_lockscreensize;
3072 offset = v2s32(0,0);
3075 double gui_scaling = g_settings->getFloat("gui_scaling");
3076 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3080 // In fixed-size mode, inventory image size
3081 // is 0.53 inch multiplied by the gui_scaling
3082 // config parameter. This magic size is chosen
3083 // to make the main menu (15.5 inventory images
3084 // wide, including border) just fit into the
3085 // default window (800 pixels wide) at 96 DPI
3086 // and default scaling (1.00).
3087 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3089 // In variable-size mode, we prefer to make the
3090 // inventory image size 1/15 of screen height,
3091 // multiplied by the gui_scaling config parameter.
3092 // If the preferred size won't fit the whole
3093 // form on the screen, either horizontally or
3094 // vertically, then we scale it down to fit.
3095 // (The magic numbers in the computation of what
3096 // fits arise from the scaling factors in the
3097 // following stanza, including the form border,
3098 // help text space, and 0.1 inventory slot spare.)
3099 // However, a minimum size is also set, that
3100 // the image size can't be less than 0.3 inch
3101 // multiplied by gui_scaling, even if this means
3102 // the form doesn't fit the screen.
3104 // For mobile devices these magic numbers are
3105 // different and forms should always use the
3106 // maximum screen space available.
3107 double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
3108 double fitx_imgsize = mydata.screensize.X /
3109 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
3110 double fity_imgsize = mydata.screensize.Y /
3111 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
3112 use_imgsize = MYMIN(prefer_imgsize,
3113 MYMIN(fitx_imgsize, fity_imgsize));
3115 double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
3116 double fitx_imgsize = mydata.screensize.X /
3117 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3118 double fity_imgsize = mydata.screensize.Y /
3119 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
3120 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3121 double min_imgsize = 0.3 * screen_dpi * gui_scaling;
3122 use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
3123 MYMIN(fitx_imgsize, fity_imgsize)));
3127 // Everything else is scaled in proportion to the
3128 // inventory image size. The inventory slot spacing
3129 // is 5/4 image size horizontally and 15/13 image size
3130 // vertically. The padding around the form (incorporating
3131 // the border of the outer inventory slots) is 3/8
3132 // image size. Font height (baseline to baseline)
3133 // is 2/5 vertical inventory slot spacing, and button
3134 // half-height is 7/8 of font height.
3135 imgsize = v2s32(use_imgsize, use_imgsize);
3136 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3137 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3138 m_btn_height = use_imgsize*15.0/13 * 0.35;
3140 m_font = g_fontengine->getFont();
3142 if (mydata.real_coordinates) {
3143 mydata.size = v2s32(
3144 mydata.invsize.X*imgsize.X,
3145 mydata.invsize.Y*imgsize.Y
3148 mydata.size = v2s32(
3149 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3150 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3154 DesiredRect = mydata.rect = core::rect<s32>(
3155 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3156 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3157 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3158 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3161 // Non-size[] form must consist only of text fields and
3162 // implicit "Proceed" button. Use default font, and
3163 // temporary form size which will be recalculated below.
3164 m_font = g_fontengine->getFont();
3165 m_btn_height = font_line_height(m_font) * 0.875;
3166 DesiredRect = core::rect<s32>(
3167 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3168 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3169 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3170 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3173 recalculateAbsolutePosition(false);
3174 mydata.basepos = getBasePos();
3175 m_tooltip_element->setOverrideFont(m_font);
3177 gui::IGUISkin *skin = Environment->getSkin();
3179 gui::IGUIFont *old_font = skin->getFont();
3180 skin->setFont(m_font);
3182 pos_offset = v2f32();
3184 // used for formspec versions < 3
3185 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3187 if (enable_prepends) {
3188 // Backup the coordinates so that prepends can use the coordinates of choice.
3189 bool rc_backup = mydata.real_coordinates;
3190 u16 version_backup = m_formspec_version;
3191 mydata.real_coordinates = false; // Old coordinates by default.
3193 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3194 for (const auto &element : prepend_elements)
3195 parseElement(&mydata, element);
3197 // legacy sorting for formspec versions < 3
3198 if (m_formspec_version >= 3)
3199 // prepends do not need to be reordered
3200 legacy_sort_start = Children.getLast();
3201 else if (version_backup >= 3)
3202 // only prepends elements have to be reordered
3203 legacySortElements(legacy_sort_start);
3205 m_formspec_version = version_backup;
3206 mydata.real_coordinates = rc_backup; // Restore coordinates
3209 for (; i< elements.size(); i++) {
3210 parseElement(&mydata, elements[i]);
3213 if (mydata.current_parent != this) {
3214 errorstream << "Invalid formspec string: scroll_container was never closed!"
3216 } else if (!container_stack.empty()) {
3217 errorstream << "Invalid formspec string: container was never closed!"
3221 // get the scrollbar elements for scroll_containers
3222 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3223 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3224 if (c.first == b.first.fname) {
3225 c.second->setScrollBar(b.second);
3231 // If there are fields without explicit size[], add a "Proceed"
3232 // button and adjust size to fit all the fields.
3233 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3234 mydata.rect = core::rect<s32>(
3235 mydata.screensize.X / 2 - 580 / 2,
3236 mydata.screensize.Y / 2 - 300 / 2,
3237 mydata.screensize.X / 2 + 580 / 2,
3238 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3241 DesiredRect = mydata.rect;
3242 recalculateAbsolutePosition(false);
3243 mydata.basepos = getBasePos();
3246 v2s32 pos = mydata.basepos;
3247 pos.Y = (mydata.simple_field_count + 2) * 60;
3249 v2s32 size = DesiredRect.getSize();
3250 mydata.rect = core::rect<s32>(
3251 size.X / 2 - 70, pos.Y,
3252 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3254 const wchar_t *text = wgettext("Proceed");
3255 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3260 //set initial focus if parser didn't set it
3261 focused_element = Environment->getFocus();
3262 if (!focused_element
3263 || !isMyChild(focused_element)
3264 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3267 skin->setFont(old_font);
3270 if (m_formspec_version < 3)
3271 legacySortElements(legacy_sort_start);
3274 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3277 Draw order for formspec_version <= 2:
3281 0 All other elements
3283 2 item_image, item_image_button
3288 if (from == Children.end())
3289 from = Children.begin();
3293 core::list<IGUIElement *>::Iterator to = Children.end();
3294 // 1: Copy into a sortable container
3295 std::vector<IGUIElement *> elements;
3296 for (auto it = from; it != to; ++it)
3297 elements.emplace_back(*it);
3299 // 2: Sort the container
3300 std::stable_sort(elements.begin(), elements.end(),
3301 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3302 const FieldSpec *spec_a = getSpecByID(a->getID());
3303 const FieldSpec *spec_b = getSpecByID(b->getID());
3304 return spec_a && spec_b &&
3305 spec_a->priority < spec_b->priority;
3308 // 3: Re-assign the pointers
3309 for (auto e : elements) {
3316 bool GUIFormSpecMenu::getAndroidUIInput()
3318 if (!hasAndroidUIInput())
3322 if (porting::getInputDialogState() == -1)
3325 std::string fieldname = m_jni_field_name;
3326 m_jni_field_name.clear();
3328 for (const FieldSpec &field : m_fields) {
3329 if (field.fname != fieldname)
3332 IGUIElement *element = getElementFromId(field.fid, true);
3334 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3337 std::string text = porting::getInputDialogValue();
3338 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3344 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3346 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3348 for (const GUIInventoryList *e : m_inventorylists) {
3349 s32 item_index = e->getItemIndexAtPos(p);
3350 if (item_index != -1)
3351 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3355 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3358 void GUIFormSpecMenu::drawSelectedItem()
3360 video::IVideoDriver* driver = Environment->getVideoDriver();
3362 if (!m_selected_item) {
3363 // reset rotation time
3364 drawItemStack(driver, m_font, ItemStack(),
3365 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3366 m_client, IT_ROT_DRAGGED);
3370 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3372 InventoryList *list = inv->getList(m_selected_item->listname);
3374 ItemStack stack = list->getItem(m_selected_item->i);
3375 stack.count = m_selected_amount;
3377 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3378 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3379 rect.constrainTo(driver->getViewPort());
3380 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3383 void GUIFormSpecMenu::drawMenu()
3386 const std::string &newform = m_form_src->getForm();
3387 if (newform != m_formspec_string) {
3388 m_formspec_string = newform;
3389 regenerateGui(m_screensize_old);
3393 gui::IGUISkin* skin = Environment->getSkin();
3394 sanity_check(skin != NULL);
3395 gui::IGUIFont *old_font = skin->getFont();
3396 skin->setFont(m_font);
3398 m_hovered_item_tooltips.clear();
3400 updateSelectedItem();
3402 video::IVideoDriver* driver = Environment->getVideoDriver();
3405 Draw background color
3407 v2u32 screenSize = driver->getScreenSize();
3408 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3411 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3412 if (m_bgnonfullscreen)
3413 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3416 Draw rect_mode tooltip
3418 m_tooltip_element->setVisible(false);
3420 for (const auto &pair : m_tooltip_rects) {
3421 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3422 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3423 const std::wstring &text = pair.second.tooltip;
3424 if (!text.empty()) {
3425 showTooltip(text, pair.second.color, pair.second.bgcolor);
3434 for (gui::IGUIElement *e : m_backgrounds) {
3435 e->setVisible(true);
3437 e->setVisible(false);
3440 // Some elements are only visible while being drawn
3441 for (gui::IGUIElement *e : m_clickthrough_elements)
3442 e->setVisible(true);
3446 (This is where all the drawing happens.)
3448 gui::IGUIElement::draw();
3450 for (gui::IGUIElement *e : m_clickthrough_elements)
3451 e->setVisible(false);
3453 // Draw hovered item tooltips
3454 for (const std::string &tooltip : m_hovered_item_tooltips) {
3455 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3456 m_default_tooltip_bgcolor);
3459 if (m_hovered_item_tooltips.empty()) {
3460 // reset rotation time
3461 drawItemStack(driver, m_font, ItemStack(),
3462 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3463 NULL, m_client, IT_ROT_HOVERED);
3466 /* TODO find way to show tooltips on touchscreen */
3467 #ifndef HAVE_TOUCHSCREENGUI
3468 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3472 Draw fields/buttons tooltips and update the mouse cursor
3474 gui::IGUIElement *hovered =
3475 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3477 #ifndef HAVE_TOUCHSCREENGUI
3478 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3480 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3482 bool hovered_element_found = false;
3484 if (hovered != NULL) {
3486 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3487 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3490 s32 id = hovered->getID();
3493 m_old_tooltip_id = id;
3495 if (id == m_old_tooltip_id) {
3496 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3498 m_hovered_time = porting::getTimeMs();
3499 m_old_tooltip_id = id;
3503 // Find and update the current tooltip and cursor icon
3505 for (const FieldSpec &field : m_fields) {
3507 if (field.fid != id)
3510 if (delta >= m_tooltip_show_delay) {
3511 const std::wstring &text = m_tooltips[field.fname].tooltip;
3513 showTooltip(text, m_tooltips[field.fname].color,
3514 m_tooltips[field.fname].bgcolor);
3517 #ifndef HAVE_TOUCHSCREENGUI
3518 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3519 current_cursor_icon != field.fcursor_icon)
3520 cursor_control->setActiveIcon(field.fcursor_icon);
3523 hovered_element_found = true;
3530 if (!hovered_element_found) {
3531 // no element is hovered
3532 #ifndef HAVE_TOUCHSCREENGUI
3533 if (current_cursor_icon != ECI_NORMAL)
3534 cursor_control->setActiveIcon(ECI_NORMAL);
3538 m_tooltip_element->draw();
3541 Draw dragged item stack
3545 skin->setFont(old_font);
3549 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3550 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3552 EnrichedString ntext(text);
3553 ntext.setDefaultColor(color);
3554 ntext.setBackground(bgcolor);
3556 setStaticText(m_tooltip_element, ntext);
3558 // Tooltip size and offset
3559 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3560 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3562 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3563 int tooltip_offset_x = m_btn_height;
3564 int tooltip_offset_y = m_btn_height;
3566 tooltip_offset_x *= 3;
3567 tooltip_offset_y = 0;
3568 if (m_pointer.X > (s32)screenSize.X / 2)
3569 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3572 // Calculate and set the tooltip position
3573 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3574 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3575 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3576 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3577 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3578 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3580 m_tooltip_element->setRelativePosition(
3582 core::position2d<s32>(tooltip_x, tooltip_y),
3583 core::dimension2d<s32>(tooltip_width, tooltip_height)
3587 // Display the tooltip
3588 m_tooltip_element->setVisible(true);
3589 bringToFront(m_tooltip_element);
3592 void GUIFormSpecMenu::updateSelectedItem()
3594 verifySelectedItem();
3596 // If craftresult is nonempty and nothing else is selected, select it now.
3597 if (!m_selected_item) {
3598 for (const GUIInventoryList *e : m_inventorylists) {
3599 if (e->getListname() != "craftpreview")
3602 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3606 InventoryList *list = inv->getList("craftresult");
3608 if (!list || list->getSize() == 0)
3611 const ItemStack &item = list->getItem(0);
3615 // Grab selected item from the crafting result list
3616 m_selected_item = new GUIInventoryList::ItemSpec;
3617 m_selected_item->inventoryloc = e->getInventoryloc();
3618 m_selected_item->listname = "craftresult";
3619 m_selected_item->i = 0;
3620 m_selected_amount = item.count;
3621 m_selected_dragging = false;
3626 // If craftresult is selected, keep the whole stack selected
3627 if (m_selected_item && m_selected_item->listname == "craftresult")
3628 m_selected_amount = verifySelectedItem().count;
3631 ItemStack GUIFormSpecMenu::verifySelectedItem()
3633 // If the selected stack has become empty for some reason, deselect it.
3634 // If the selected stack has become inaccessible, deselect it.
3635 // If the selected stack has become smaller, adjust m_selected_amount.
3636 // Return the selected stack.
3638 if (m_selected_item) {
3639 if (m_selected_item->isValid()) {
3640 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3642 InventoryList *list = inv->getList(m_selected_item->listname);
3643 if (list && (u32) m_selected_item->i < list->getSize()) {
3644 ItemStack stack = list->getItem(m_selected_item->i);
3645 if (!m_selected_swap.empty()) {
3646 if (m_selected_swap.name == stack.name &&
3647 m_selected_swap.count == stack.count)
3648 m_selected_swap.clear();
3650 m_selected_amount = std::min(m_selected_amount, stack.count);
3659 // selection was not valid
3660 delete m_selected_item;
3661 m_selected_item = nullptr;
3662 m_selected_amount = 0;
3663 m_selected_dragging = false;
3668 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3674 if (quitmode == quit_mode_accept) {
3675 fields["quit"] = "true";
3678 if (quitmode == quit_mode_cancel) {
3679 fields["quit"] = "true";
3680 m_text_dst->gotText(fields);
3684 if (current_keys_pending.key_down) {
3685 fields["key_down"] = "true";
3686 current_keys_pending.key_down = false;
3689 if (current_keys_pending.key_up) {
3690 fields["key_up"] = "true";
3691 current_keys_pending.key_up = false;
3694 if (current_keys_pending.key_enter) {
3695 fields["key_enter"] = "true";
3696 current_keys_pending.key_enter = false;
3699 if (!current_field_enter_pending.empty()) {
3700 fields["key_enter_field"] = current_field_enter_pending;
3701 current_field_enter_pending = "";
3704 if (current_keys_pending.key_escape) {
3705 fields["key_escape"] = "true";
3706 current_keys_pending.key_escape = false;
3709 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3711 std::string name = s.fname;
3712 if (s.ftype == f_Button) {
3713 fields[name] = wide_to_utf8(s.flabel);
3714 } else if (s.ftype == f_Table) {
3715 GUITable *table = getTable(s.fname);
3717 fields[name] = table->checkEvent();
3719 } else if (s.ftype == f_DropDown) {
3720 // No dynamic cast possible due to some distributions shipped
3721 // without rtti support in Irrlicht
3722 IGUIElement *element = getElementFromId(s.fid, true);
3723 gui::IGUIComboBox *e = NULL;
3724 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3725 e = static_cast<gui::IGUIComboBox *>(element);
3727 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3728 << "field without dropdown element" << std::endl;
3731 s32 selected = e->getSelected();
3732 if (selected >= 0) {
3733 std::vector<std::string> *dropdown_values =
3734 getDropDownValues(s.fname);
3735 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3736 fields[name] = (*dropdown_values)[selected];
3739 } else if (s.ftype == f_TabHeader) {
3740 // No dynamic cast possible due to some distributions shipped
3741 // without rtti support in Irrlicht
3742 IGUIElement *element = getElementFromId(s.fid, true);
3743 gui::IGUITabControl *e = nullptr;
3744 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3745 e = static_cast<gui::IGUITabControl *>(element);
3749 std::stringstream ss;
3750 ss << (e->getActiveTab() +1);
3751 fields[name] = ss.str();
3753 } else if (s.ftype == f_CheckBox) {
3754 // No dynamic cast possible due to some distributions shipped
3755 // without rtti support in Irrlicht
3756 IGUIElement *element = getElementFromId(s.fid, true);
3757 gui::IGUICheckBox *e = nullptr;
3758 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3759 e = static_cast<gui::IGUICheckBox*>(element);
3764 fields[name] = "true";
3766 fields[name] = "false";
3768 } else if (s.ftype == f_ScrollBar) {
3769 // No dynamic cast possible due to some distributions shipped
3770 // without rtti support in Irrlicht
3771 IGUIElement *element = getElementFromId(s.fid, true);
3772 GUIScrollBar *e = nullptr;
3773 if (element && element->getType() == gui::EGUIET_ELEMENT)
3774 e = static_cast<GUIScrollBar *>(element);
3777 std::stringstream os;
3779 if (s.fdefault == L"Changed")
3780 fields[name] = "CHG:" + os.str();
3782 fields[name] = "VAL:" + os.str();
3784 } else if (s.ftype == f_AnimatedImage) {
3785 // No dynamic cast possible due to some distributions shipped
3786 // without rtti support in Irrlicht
3787 IGUIElement *element = getElementFromId(s.fid, true);
3788 GUIAnimatedImage *e = nullptr;
3789 if (element && element->getType() == gui::EGUIET_ELEMENT)
3790 e = static_cast<GUIAnimatedImage *>(element);
3793 fields[name] = std::to_string(e->getFrameIndex() + 1);
3795 IGUIElement *e = getElementFromId(s.fid, true);
3797 fields[name] = wide_to_utf8(e->getText());
3802 m_text_dst->gotText(fields);
3806 static bool isChild(gui::IGUIElement *tocheck, gui::IGUIElement *parent)
3809 if (tocheck == parent) {
3812 tocheck = tocheck->getParent();
3817 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3819 // The IGUITabControl renders visually using the skin's selected
3820 // font, which we override for the duration of form drawing,
3821 // but computes tab hotspots based on how it would have rendered
3822 // using the font that is selected at the time of button release.
3823 // To make these two consistent, temporarily override the skin's
3824 // font while the IGUITabControl is processing the event.
3825 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3826 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3827 s32 x = event.MouseInput.X;
3828 s32 y = event.MouseInput.Y;
3829 gui::IGUIElement *hovered =
3830 Environment->getRootGUIElement()->getElementFromPoint(
3831 core::position2d<s32>(x, y));
3832 if (hovered && isMyChild(hovered) &&
3833 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3834 gui::IGUISkin* skin = Environment->getSkin();
3835 sanity_check(skin != NULL);
3836 gui::IGUIFont *old_font = skin->getFont();
3837 skin->setFont(m_font);
3838 bool retval = hovered->OnEvent(event);
3839 skin->setFont(old_font);
3844 // Fix Esc/Return key being eaten by checkboxen and tables
3845 if (event.EventType == EET_KEY_INPUT_EVENT) {
3846 KeyPress kp(event.KeyInput);
3847 if (kp == EscapeKey || kp == CancelKey
3848 || kp == getKeySetting("keymap_inventory")
3849 || event.KeyInput.Key==KEY_RETURN) {
3850 gui::IGUIElement *focused = Environment->getFocus();
3851 if (focused && isMyChild(focused) &&
3852 (focused->getType() == gui::EGUIET_LIST_BOX ||
3853 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3854 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3855 event.KeyInput.Key != KEY_RETURN)) {
3861 // Mouse wheel and move events: send to hovered element instead of focused
3862 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3863 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3864 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3865 event.MouseInput.ButtonStates == 0))) {
3866 s32 x = event.MouseInput.X;
3867 s32 y = event.MouseInput.Y;
3868 gui::IGUIElement *hovered =
3869 Environment->getRootGUIElement()->getElementFromPoint(
3870 core::position2d<s32>(x, y));
3871 if (hovered && isMyChild(hovered)) {
3872 hovered->OnEvent(event);
3873 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3877 if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3878 s32 x = event.MouseInput.X;
3879 s32 y = event.MouseInput.Y;
3880 gui::IGUIElement *hovered =
3881 Environment->getRootGUIElement()->getElementFromPoint(
3882 core::position2d<s32>(x, y));
3883 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3884 m_old_tooltip_id = -1;
3886 if (!isChild(hovered, this)) {
3887 if (DoubleClickDetection(event)) {
3893 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3894 /* TODO add a check like:
3895 if (event.JoystickEvent != joystick_we_listen_for)
3898 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3900 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3902 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3904 acceptInput(quit_mode_accept);
3912 return GUIModalMenu::preprocessEvent(event);
3915 /******************************************************************************/
3916 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3918 /* The following code is for capturing double-clicks of the mouse button
3919 * and translating the double-click into an EET_KEY_INPUT_EVENT event
3920 * -- which closes the form -- under some circumstances.
3922 * There have been many github issues reporting this as a bug even though it
3923 * was an intended feature. For this reason, remapping the double-click as
3924 * an ESC must be explicitly set when creating this class via the
3925 * /p remap_dbl_click parameter of the constructor.
3928 if (!m_remap_dbl_click)
3931 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3932 m_doubleclickdetect[0].pos = m_doubleclickdetect[1].pos;
3933 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3935 m_doubleclickdetect[1].pos = m_pointer;
3936 m_doubleclickdetect[1].time = porting::getTimeMs();
3938 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3939 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3944 double squaredistance =
3945 m_doubleclickdetect[0].pos
3946 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3948 if (squaredistance > (30*30)) {
3952 SEvent* translated = new SEvent();
3953 assert(translated != 0);
3954 //translate doubleclick to escape
3955 memset(translated, 0, sizeof(SEvent));
3956 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3957 translated->KeyInput.Key = KEY_ESCAPE;
3958 translated->KeyInput.Control = false;
3959 translated->KeyInput.Shift = false;
3960 translated->KeyInput.PressedDown = true;
3961 translated->KeyInput.Char = 0;
3962 OnEvent(*translated);
3964 // no need to send the key up event as we're already deleted
3965 // and no one else did notice this event
3973 void GUIFormSpecMenu::tryClose()
3977 acceptInput(quit_mode_cancel);
3980 m_text_dst->gotText(L"MenuQuit");
3984 enum ButtonEventType : u8
3997 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3999 if (event.EventType==EET_KEY_INPUT_EVENT) {
4000 KeyPress kp(event.KeyInput);
4001 if (event.KeyInput.PressedDown && (
4002 (kp == EscapeKey) || (kp == CancelKey) ||
4003 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4008 if (m_client != NULL && event.KeyInput.PressedDown &&
4009 (kp == getKeySetting("keymap_screenshot"))) {
4010 m_client->makeScreenshot();
4013 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4014 m_show_debug = !m_show_debug;
4016 if (event.KeyInput.PressedDown &&
4017 (event.KeyInput.Key==KEY_RETURN ||
4018 event.KeyInput.Key==KEY_UP ||
4019 event.KeyInput.Key==KEY_DOWN)
4021 switch (event.KeyInput.Key) {
4023 current_keys_pending.key_enter = true;
4026 current_keys_pending.key_up = true;
4029 current_keys_pending.key_down = true;
4033 //can't happen at all!
4034 FATAL_ERROR("Reached a source line that can't ever been reached");
4037 if (current_keys_pending.key_enter && m_allowclose) {
4038 acceptInput(quit_mode_accept);
4048 /* Mouse event other than movement, or crossing the border of inventory
4049 field while holding right mouse button
4051 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4052 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4053 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4054 event.MouseInput.isRightPressed() &&
4055 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4057 // Get selected item and hovered/clicked item (s)
4059 m_old_tooltip_id = -1;
4060 updateSelectedItem();
4061 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4063 Inventory *inv_selected = NULL;
4064 Inventory *inv_s = NULL;
4065 InventoryList *list_s = NULL;
4067 if (m_selected_item) {
4068 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4069 sanity_check(inv_selected);
4070 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4077 inv_s = m_invmgr->getInventory(s.inventoryloc);
4080 errorstream << "InventoryMenu: The selected inventory location "
4081 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4083 s.i = -1; // make it invalid again
4087 list_s = inv_s->getList(s.listname);
4088 if (list_s == NULL) {
4089 verbosestream << "InventoryMenu: The selected inventory list \""
4090 << s.listname << "\" does not exist" << std::endl;
4091 s.i = -1; // make it invalid again
4095 if ((u32)s.i >= list_s->getSize()) {
4096 infostream << "InventoryMenu: The selected inventory list \""
4097 << s.listname << "\" is too small (i=" << s.i << ", size="
4098 << list_s->getSize() << ")" << std::endl;
4099 s.i = -1; // make it invalid again
4103 s_count = list_s->getItem(s.i).count;
4106 bool identical = m_selected_item && s.isValid() &&
4107 (inv_selected == inv_s) &&
4108 (m_selected_item->listname == s.listname) &&
4109 (m_selected_item->i == s.i);
4111 ButtonEventType button = BET_LEFT;
4112 ButtonEventType updown = BET_OTHER;
4113 switch (event.MouseInput.Event) {
4114 case EMIE_LMOUSE_PRESSED_DOWN:
4115 button = BET_LEFT; updown = BET_DOWN;
4117 case EMIE_RMOUSE_PRESSED_DOWN:
4118 button = BET_RIGHT; updown = BET_DOWN;
4120 case EMIE_MMOUSE_PRESSED_DOWN:
4121 button = BET_MIDDLE; updown = BET_DOWN;
4123 case EMIE_MOUSE_WHEEL:
4124 button = (event.MouseInput.Wheel > 0) ?
4125 BET_WHEEL_UP : BET_WHEEL_DOWN;
4128 case EMIE_LMOUSE_LEFT_UP:
4129 button = BET_LEFT; updown = BET_UP;
4131 case EMIE_RMOUSE_LEFT_UP:
4132 button = BET_RIGHT; updown = BET_UP;
4134 case EMIE_MMOUSE_LEFT_UP:
4135 button = BET_MIDDLE; updown = BET_UP;
4137 case EMIE_MOUSE_MOVED:
4144 // Set this number to a positive value to generate a move action
4145 // from m_selected_item to s.
4146 u32 move_amount = 0;
4148 // Set this number to a positive value to generate a move action
4149 // from s to the next inventory ring.
4150 u32 shift_move_amount = 0;
4152 // Set this number to a positive value to generate a drop action
4153 // from m_selected_item.
4154 u32 drop_amount = 0;
4156 // Set this number to a positive value to generate a craft action at s.
4157 u32 craft_amount = 0;
4161 // Some mouse button has been pressed
4163 //infostream << "Mouse button " << button << " pressed at p=("
4164 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4167 m_selected_dragging = false;
4169 if (s.isValid() && s.listname == "craftpreview") {
4170 // Craft preview has been clicked: craft
4171 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4172 } else if (!m_selected_item) {
4173 if (s_count && button != BET_WHEEL_UP) {
4174 // Non-empty stack has been clicked: select or shift-move it
4175 m_selected_item = new GUIInventoryList::ItemSpec(s);
4178 if (button == BET_RIGHT)
4179 count = (s_count + 1) / 2;
4180 else if (button == BET_MIDDLE)
4181 count = MYMIN(s_count, 10);
4182 else if (button == BET_WHEEL_DOWN)
4187 if (!event.MouseInput.Shift) {
4188 // no shift: select item
4189 m_selected_amount = count;
4190 m_selected_dragging = button != BET_WHEEL_DOWN;
4191 m_auto_place = false;
4193 // shift pressed: move item, right click moves 1
4194 shift_move_amount = button == BET_RIGHT ? 1 : count;
4197 } else { // m_selected_item != NULL
4198 assert(m_selected_amount >= 1);
4201 // Clicked a slot: move
4202 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4204 else if (button == BET_MIDDLE)
4205 move_amount = MYMIN(m_selected_amount, 10);
4206 else if (button == BET_LEFT)
4207 move_amount = m_selected_amount;
4211 if (button == BET_WHEEL_DOWN) {
4212 if (m_selected_amount < s_count)
4213 ++m_selected_amount;
4215 if (move_amount >= m_selected_amount)
4216 m_selected_amount = 0;
4218 m_selected_amount -= move_amount;
4222 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4223 && button != BET_WHEEL_DOWN) {
4224 // Clicked outside of the window: drop
4225 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4227 else if (button == BET_MIDDLE)
4228 drop_amount = MYMIN(m_selected_amount, 10);
4230 drop_amount = m_selected_amount;
4235 // Some mouse button has been released
4237 //infostream<<"Mouse button "<<button<<" released at p=("
4238 // <<p.X<<","<<p.Y<<")"<<std::endl;
4240 if (m_selected_dragging && m_selected_item) {
4243 // Dragged to different slot: move all selected
4244 move_amount = m_selected_amount;
4246 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4247 // Dragged outside of window: drop all selected
4248 drop_amount = m_selected_amount;
4252 m_selected_dragging = false;
4253 // Keep track of whether the mouse button be released
4254 // One click is drag without dropping. Click + release
4255 // + click changes to drop item when moved mode
4256 if (m_selected_item)
4257 m_auto_place = true;
4260 // Mouse has been moved and rmb is down and mouse pointer just
4261 // entered a new inventory field (checked in the entry-if, this
4262 // is the only action here that is generated by mouse movement)
4263 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4265 // TODO: middle mouse to move 10 items might be handy
4267 // Only move an item if the destination slot is empty
4268 // or contains the same item type as what is going to be
4270 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4271 InventoryList *list_to = list_s;
4272 assert(list_from && list_to);
4273 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4274 ItemStack stack_to = list_to->getItem(s.i);
4275 if (stack_to.empty() || stack_to.name == stack_from.name)
4284 // Possibly send inventory action to server
4285 if (move_amount > 0) {
4286 // Send IAction::Move
4288 assert(m_selected_item && m_selected_item->isValid());
4289 assert(s.isValid());
4291 assert(inv_selected && inv_s);
4292 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4293 InventoryList *list_to = list_s;
4294 assert(list_from && list_to);
4295 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4296 ItemStack stack_to = list_to->getItem(s.i);
4298 // Check how many items can be moved
4299 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4300 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4302 // If source stack cannot be added to destination stack at all,
4304 if (leftover.count == stack_from.count &&
4305 leftover.name == stack_from.name) {
4307 if (m_selected_swap.empty()) {
4308 m_selected_amount = stack_to.count;
4309 m_selected_dragging = false;
4311 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4312 // Skip next validation checks due async inventory calls
4313 m_selected_swap = stack_to;
4318 // Source stack goes fully into destination stack
4319 else if (leftover.empty()) {
4320 m_selected_amount -= move_amount;
4322 // Source stack goes partly into destination stack
4324 move_amount -= leftover.count;
4325 m_selected_amount -= move_amount;
4329 infostream << "Handing IAction::Move to manager" << std::endl;
4330 IMoveAction *a = new IMoveAction();
4331 a->count = move_amount;
4332 a->from_inv = m_selected_item->inventoryloc;
4333 a->from_list = m_selected_item->listname;
4334 a->from_i = m_selected_item->i;
4335 a->to_inv = s.inventoryloc;
4336 a->to_list = s.listname;
4338 m_invmgr->inventoryAction(a);
4340 } else if (shift_move_amount > 0) {
4341 u32 mis = m_inventory_rings.size();
4343 for (; i < mis; i++) {
4344 const ListRingSpec &sp = m_inventory_rings[i];
4345 if (sp.inventoryloc == s.inventoryloc
4346 && sp.listname == s.listname)
4350 if (i >= mis) // if not found
4352 u32 to_inv_ind = (i + 1) % mis;
4353 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4354 InventoryList *list_from = list_s;
4357 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4360 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4363 ItemStack stack_from = list_from->getItem(s.i);
4364 assert(shift_move_amount <= stack_from.count);
4366 infostream << "Handing IAction::Move to manager" << std::endl;
4367 IMoveAction *a = new IMoveAction();
4368 a->count = shift_move_amount;
4369 a->from_inv = s.inventoryloc;
4370 a->from_list = s.listname;
4372 a->to_inv = to_inv_sp.inventoryloc;
4373 a->to_list = to_inv_sp.listname;
4374 a->move_somewhere = true;
4375 m_invmgr->inventoryAction(a);
4377 } else if (drop_amount > 0) {
4378 // Send IAction::Drop
4380 assert(m_selected_item && m_selected_item->isValid());
4381 assert(inv_selected);
4382 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4384 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4386 // Check how many items can be dropped
4387 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4388 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4389 m_selected_amount -= drop_amount;
4391 infostream << "Handing IAction::Drop to manager" << std::endl;
4392 IDropAction *a = new IDropAction();
4393 a->count = drop_amount;
4394 a->from_inv = m_selected_item->inventoryloc;
4395 a->from_list = m_selected_item->listname;
4396 a->from_i = m_selected_item->i;
4397 m_invmgr->inventoryAction(a);
4398 } else if (craft_amount > 0) {
4399 assert(s.isValid());
4401 // if there are no items selected or the selected item
4402 // belongs to craftresult list, proceed with crafting
4403 if (!m_selected_item ||
4404 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4408 // Send IACTION_CRAFT
4409 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4410 ICraftAction *a = new ICraftAction();
4411 a->count = craft_amount;
4412 a->craft_inv = s.inventoryloc;
4413 m_invmgr->inventoryAction(a);
4417 // If m_selected_amount has been decreased to zero, deselect
4418 if (m_selected_amount == 0) {
4419 m_selected_swap.clear();
4420 delete m_selected_item;
4421 m_selected_item = nullptr;
4422 m_selected_amount = 0;
4423 m_selected_dragging = false;
4425 m_old_pointer = m_pointer;
4428 if (event.EventType == EET_GUI_EVENT) {
4429 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4431 // find the element that was clicked
4432 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4433 if ((s.ftype == f_TabHeader) &&
4434 (s.fid == event.GUIEvent.Caller->getID())) {
4442 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4444 if (!canTakeFocus(event.GUIEvent.Element)) {
4445 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4447 // Returning true disables focus change
4451 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4452 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4453 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4454 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4455 s32 caller_id = event.GUIEvent.Caller->getID();
4457 if (caller_id == 257) {
4459 acceptInput(quit_mode_accept);
4463 m_text_dst->gotText(L"ExitButton");
4465 // quitMenu deallocates menu
4469 // find the element that was clicked
4470 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4471 // if its a button, set the send field so
4472 // lua knows which button was pressed
4474 if (caller_id != s.fid)
4477 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4481 acceptInput(quit_mode_accept);
4484 m_text_dst->gotText(L"ExitButton");
4489 acceptInput(quit_mode_no);
4493 } else if (s.ftype == f_DropDown) {
4494 // only send the changed dropdown
4495 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4496 if (s2.ftype == f_DropDown) {
4501 acceptInput(quit_mode_no);
4503 // revert configuration to make sure dropdowns are sent on
4504 // regular button click
4505 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4506 if (s2.ftype == f_DropDown) {
4511 } else if (s.ftype == f_ScrollBar) {
4512 s.fdefault = L"Changed";
4513 acceptInput(quit_mode_no);
4515 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4523 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4524 // move scroll_containers
4525 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4526 c.second->onScrollEvent(event.GUIEvent.Caller);
4529 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4530 if (event.GUIEvent.Caller->getID() > 257) {
4531 bool close_on_enter = true;
4532 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4533 if (s.ftype == f_Unknown &&
4534 s.fid == event.GUIEvent.Caller->getID()) {
4535 current_field_enter_pending = s.fname;
4536 std::unordered_map<std::string, bool>::const_iterator it =
4537 field_close_on_enter.find(s.fname);
4538 if (it != field_close_on_enter.end())
4539 close_on_enter = (*it).second;
4545 if (m_allowclose && close_on_enter) {
4546 current_keys_pending.key_enter = true;
4547 acceptInput(quit_mode_accept);
4550 current_keys_pending.key_enter = true;
4553 // quitMenu deallocates menu
4558 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4559 int current_id = event.GUIEvent.Caller->getID();
4560 if (current_id > 257) {
4561 // find the element that was clicked
4562 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4563 // if it's a table, set the send field
4564 // so lua knows which table was changed
4565 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4576 return Parent ? Parent->OnEvent(event) : false;
4580 * get name of element by element id
4581 * @param id of element
4582 * @return name string or empty string
4584 std::string GUIFormSpecMenu::getNameByID(s32 id)
4586 for (FieldSpec &spec : m_fields) {
4594 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4596 for (FieldSpec &spec : m_fields) {
4604 * get label of element by id
4605 * @param id of element
4606 * @return label string or empty string
4608 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4610 for (FieldSpec &spec : m_fields) {
4617 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4618 const std::string &name, const std::string &parent_type) {
4619 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4622 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(const std::string &type,
4623 const std::string &name, const std::string &parent_type)
4625 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4627 if (!parent_type.empty()) {
4628 auto it = theme_by_type.find(parent_type);
4629 if (it != theme_by_type.end()) {
4630 for (const StyleSpec &spec : it->second)
4631 ret[(u32)spec.getState()] |= spec;
4635 auto it = theme_by_type.find(type);
4636 if (it != theme_by_type.end()) {
4637 for (const StyleSpec &spec : it->second)
4638 ret[(u32)spec.getState()] |= spec;
4641 it = theme_by_name.find(name);
4642 if (it != theme_by_name.end()) {
4643 for (const StyleSpec &spec : it->second)
4644 ret[(u32)spec.getState()] |= spec;