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));
919 // Animated images should let events through
920 m_clickthrough_elements.push_back(e);
922 m_fields.push_back(spec);
925 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
927 std::vector<std::string> parts = split(element,';');
929 if ((parts.size() == 3) ||
930 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
932 std::vector<std::string> v_pos = split(parts[0],',');
933 std::vector<std::string> v_geom = split(parts[1],',');
934 std::string name = parts[2];
936 MY_CHECKPOS("itemimage",0);
937 MY_CHECKGEOM("itemimage",1);
942 if (data->real_coordinates) {
943 pos = getRealCoordinateBasePos(v_pos);
944 geom = getRealCoordinateGeometry(v_geom);
946 pos = getElementBasePos(&v_pos);
947 geom.X = stof(v_geom[0]) * (float)imgsize.X;
948 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
951 if(!data->explicit_size)
952 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
958 258 + m_fields.size(),
961 spec.ftype = f_ItemImage;
963 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
964 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
965 auto style = getDefaultStyleForElement("item_image", spec.fname);
966 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
968 // item images should let events through
969 m_clickthrough_elements.push_back(e);
971 m_fields.push_back(spec);
974 errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
977 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
978 const std::string &type)
980 std::vector<std::string> parts = split(element,';');
982 if ((parts.size() == 4) ||
983 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
985 std::vector<std::string> v_pos = split(parts[0],',');
986 std::vector<std::string> v_geom = split(parts[1],',');
987 std::string name = parts[2];
988 std::string label = parts[3];
990 MY_CHECKPOS("button",0);
991 MY_CHECKGEOM("button",1);
995 core::rect<s32> rect;
997 if (data->real_coordinates) {
998 pos = getRealCoordinateBasePos(v_pos);
999 geom = getRealCoordinateGeometry(v_geom);
1000 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1003 pos = getElementBasePos(&v_pos);
1004 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1005 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1007 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
1008 pos.X + geom.X, pos.Y + m_btn_height);
1011 if(!data->explicit_size)
1012 warningstream<<"invalid use of button without a size[] element"<<std::endl;
1014 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1020 258 + m_fields.size()
1022 spec.ftype = f_Button;
1023 if(type == "button_exit")
1024 spec.is_exit = true;
1026 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1027 data->current_parent, spec.fid, spec.flabel.c_str());
1029 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1030 e->setStyles(style);
1032 if (spec.fname == data->focused_fieldname) {
1033 Environment->setFocus(e);
1036 m_fields.push_back(spec);
1039 errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl;
1042 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1044 std::vector<std::string> parts = split(element,';');
1046 if ((parts.size() >= 3 && parts.size() <= 5) ||
1047 (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
1048 std::vector<std::string> v_pos = split(parts[0],',');
1049 std::vector<std::string> v_geom = split(parts[1],',');
1050 std::string name = unescape_string(parts[2]);
1052 MY_CHECKPOS("background",0);
1053 MY_CHECKGEOM("background",1);
1058 if (data->real_coordinates) {
1059 pos = getRealCoordinateBasePos(v_pos);
1060 geom = getRealCoordinateGeometry(v_geom);
1062 pos = getElementBasePos(&v_pos);
1063 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1064 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1066 geom.X = stof(v_geom[0]) * spacing.X;
1067 geom.Y = stof(v_geom[1]) * spacing.Y;
1071 if (parts.size() >= 4 && is_yes(parts[3])) {
1072 if (data->real_coordinates) {
1073 pos = getRealCoordinateBasePos(v_pos) * -1;
1076 pos.X = stoi(v_pos[0]); //acts as offset
1077 pos.Y = stoi(v_pos[1]);
1082 core::rect<s32> middle;
1083 if (parts.size() >= 5) {
1084 std::vector<std::string> v_middle = split(parts[4], ',');
1085 if (v_middle.size() == 1) {
1086 s32 x = stoi(v_middle[0]);
1087 middle.UpperLeftCorner = core::vector2di(x, x);
1088 middle.LowerRightCorner = core::vector2di(-x, -x);
1089 } else if (v_middle.size() == 2) {
1090 s32 x = stoi(v_middle[0]);
1091 s32 y = stoi(v_middle[1]);
1092 middle.UpperLeftCorner = core::vector2di(x, y);
1093 middle.LowerRightCorner = core::vector2di(-x, -y);
1094 // `-x` is interpreted as `w - x`
1095 } else if (v_middle.size() == 4) {
1096 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1097 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1099 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1103 if (!data->explicit_size && !clip)
1104 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1110 258 + m_fields.size()
1113 core::rect<s32> rect;
1115 // no auto_clip => position like normal image
1116 rect = core::rect<s32>(pos, pos + geom);
1118 // it will be auto-clipped when drawing
1119 rect = core::rect<s32>(-pos, pos);
1122 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1123 rect, name, middle, m_tsrc, clip);
1125 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1127 e->setNotClipped(true);
1129 e->setVisible(false); // the element is drawn manually before all others
1131 m_backgrounds.push_back(e);
1132 m_fields.push_back(spec);
1135 errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl;
1138 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1140 std::vector<std::string> parts = split(element,';');
1142 data->table_options.clear();
1143 for (const std::string &part : parts) {
1144 // Parse table option
1145 std::string opt = unescape_string(part);
1146 data->table_options.push_back(GUITable::splitOption(opt));
1150 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1152 std::vector<std::string> parts = split(element,';');
1154 data->table_columns.clear();
1155 for (const std::string &part : parts) {
1156 std::vector<std::string> col_parts = split(part,',');
1157 GUITable::TableColumn column;
1158 // Parse column type
1159 if (!col_parts.empty())
1160 column.type = col_parts[0];
1161 // Parse column options
1162 for (size_t j = 1; j < col_parts.size(); ++j) {
1163 std::string opt = unescape_string(col_parts[j]);
1164 column.options.push_back(GUITable::splitOption(opt));
1166 data->table_columns.push_back(column);
1170 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1172 std::vector<std::string> parts = split(element,';');
1174 if (((parts.size() == 4) || (parts.size() == 5)) ||
1175 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1177 std::vector<std::string> v_pos = split(parts[0],',');
1178 std::vector<std::string> v_geom = split(parts[1],',');
1179 std::string name = parts[2];
1180 std::vector<std::string> items = split(parts[3],',');
1181 std::string str_initial_selection;
1182 std::string str_transparent = "false";
1184 if (parts.size() >= 5)
1185 str_initial_selection = parts[4];
1187 MY_CHECKPOS("table",0);
1188 MY_CHECKGEOM("table",1);
1193 if (data->real_coordinates) {
1194 pos = getRealCoordinateBasePos(v_pos);
1195 geom = getRealCoordinateGeometry(v_geom);
1197 pos = getElementBasePos(&v_pos);
1198 geom.X = stof(v_geom[0]) * spacing.X;
1199 geom.Y = stof(v_geom[1]) * spacing.Y;
1202 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1208 258 + m_fields.size()
1211 spec.ftype = f_Table;
1213 for (std::string &item : items) {
1214 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1217 //now really show table
1218 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1221 if (spec.fname == data->focused_fieldname) {
1222 Environment->setFocus(e);
1225 e->setTable(data->table_options, data->table_columns, items);
1227 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1228 e->setDynamicData(data->table_dyndata[name]);
1231 if (!str_initial_selection.empty() && str_initial_selection != "0")
1232 e->setSelected(stoi(str_initial_selection));
1234 auto style = getDefaultStyleForElement("table", name);
1235 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1237 m_tables.emplace_back(spec, e);
1238 m_fields.push_back(spec);
1241 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1244 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1246 std::vector<std::string> parts = split(element,';');
1248 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1249 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1251 std::vector<std::string> v_pos = split(parts[0],',');
1252 std::vector<std::string> v_geom = split(parts[1],',');
1253 std::string name = parts[2];
1254 std::vector<std::string> items = split(parts[3],',');
1255 std::string str_initial_selection;
1256 std::string str_transparent = "false";
1258 if (parts.size() >= 5)
1259 str_initial_selection = parts[4];
1261 if (parts.size() >= 6)
1262 str_transparent = parts[5];
1264 MY_CHECKPOS("textlist",0);
1265 MY_CHECKGEOM("textlist",1);
1270 if (data->real_coordinates) {
1271 pos = getRealCoordinateBasePos(v_pos);
1272 geom = getRealCoordinateGeometry(v_geom);
1274 pos = getElementBasePos(&v_pos);
1275 geom.X = stof(v_geom[0]) * spacing.X;
1276 geom.Y = stof(v_geom[1]) * spacing.Y;
1279 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1285 258 + m_fields.size()
1288 spec.ftype = f_Table;
1290 for (std::string &item : items) {
1291 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1294 //now really show list
1295 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1298 if (spec.fname == data->focused_fieldname) {
1299 Environment->setFocus(e);
1302 e->setTextList(items, is_yes(str_transparent));
1304 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1305 e->setDynamicData(data->table_dyndata[name]);
1308 if (!str_initial_selection.empty() && str_initial_selection != "0")
1309 e->setSelected(stoi(str_initial_selection));
1311 auto style = getDefaultStyleForElement("textlist", name);
1312 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1314 m_tables.emplace_back(spec, e);
1315 m_fields.push_back(spec);
1318 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1322 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1324 std::vector<std::string> parts = split(element,';');
1326 if ((parts.size() == 5) ||
1327 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1329 std::vector<std::string> v_pos = split(parts[0],',');
1330 std::string name = parts[2];
1331 std::vector<std::string> items = split(parts[3],',');
1332 std::string str_initial_selection;
1333 str_initial_selection = parts[4];
1335 MY_CHECKPOS("dropdown",0);
1339 core::rect<s32> rect;
1341 if (data->real_coordinates) {
1342 std::vector<std::string> v_geom = split(parts[1],',');
1344 if (v_geom.size() == 1)
1345 v_geom.emplace_back("1");
1347 MY_CHECKGEOM("dropdown",1);
1349 pos = getRealCoordinateBasePos(v_pos);
1350 geom = getRealCoordinateGeometry(v_geom);
1351 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1353 pos = getElementBasePos(&v_pos);
1355 s32 width = stof(parts[1]) * spacing.Y;
1357 rect = core::rect<s32>(pos.X, pos.Y,
1358 pos.X + width, pos.Y + (m_btn_height * 2));
1365 258 + m_fields.size()
1368 spec.ftype = f_DropDown;
1371 //now really show list
1372 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1375 if (spec.fname == data->focused_fieldname) {
1376 Environment->setFocus(e);
1379 for (const std::string &item : items) {
1380 e->addItem(unescape_translate(unescape_string(
1381 utf8_to_wide(item))).c_str());
1384 if (!str_initial_selection.empty())
1385 e->setSelected(stoi(str_initial_selection)-1);
1387 auto style = getDefaultStyleForElement("dropdown", name);
1388 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1390 m_fields.push_back(spec);
1392 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1393 std::vector<std::string> &values = m_dropdowns.back().second;
1394 for (const std::string &item : items) {
1395 values.push_back(unescape_string(item));
1400 errorstream << "Invalid dropdown element(" << parts.size() << "): '"
1401 << element << "'" << std::endl;
1404 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1406 std::vector<std::string> parts = split(element,';');
1407 if (parts.size() == 2 ||
1408 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1409 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1413 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1415 std::vector<std::string> parts = split(element,';');
1417 if ((parts.size() == 4) ||
1418 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
1420 std::vector<std::string> v_pos = split(parts[0],',');
1421 std::vector<std::string> v_geom = split(parts[1],',');
1422 std::string name = parts[2];
1423 std::string label = parts[3];
1425 MY_CHECKPOS("pwdfield",0);
1426 MY_CHECKGEOM("pwdfield",1);
1431 if (data->real_coordinates) {
1432 pos = getRealCoordinateBasePos(v_pos);
1433 geom = getRealCoordinateGeometry(v_geom);
1435 pos = getElementBasePos(&v_pos);
1438 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1440 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1441 pos.Y -= m_btn_height;
1442 geom.Y = m_btn_height*2;
1445 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1447 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1453 258 + m_fields.size(),
1459 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1460 data->current_parent, spec.fid);
1462 if (spec.fname == data->focused_fieldname) {
1463 Environment->setFocus(e);
1466 if (label.length() >= 1) {
1467 int font_height = g_fontengine->getTextHeight();
1468 rect.UpperLeftCorner.Y -= font_height;
1469 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1470 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1471 data->current_parent, 0);
1474 e->setPasswordBox(true,L'*');
1476 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1477 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1478 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1479 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1482 evt.EventType = EET_KEY_INPUT_EVENT;
1483 evt.KeyInput.Key = KEY_END;
1484 evt.KeyInput.Char = 0;
1485 evt.KeyInput.Control = false;
1486 evt.KeyInput.Shift = false;
1487 evt.KeyInput.PressedDown = true;
1490 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1491 // warning referring to field_close_on_enter[]!
1493 m_fields.push_back(spec);
1496 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1499 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1500 core::rect<s32> &rect, bool is_multiline)
1502 bool is_editable = !spec.fname.empty();
1503 if (!is_editable && !is_multiline) {
1504 // spec field id to 0, this stops submit searching for a value that isn't there
1505 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1506 data->current_parent, 0);
1512 } else if (is_multiline &&
1513 spec.fdefault.empty() && !spec.flabel.empty()) {
1514 // Multiline textareas: swap default and label for backwards compat
1515 spec.flabel.swap(spec.fdefault);
1518 gui::IGUIEditBox *e = nullptr;
1519 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1520 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1522 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1523 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1524 data->current_parent, spec.fid, rect, is_editable, is_multiline);
1527 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1528 data->current_parent, spec.fid, rect, is_editable, true);
1529 } else if (is_editable) {
1530 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1531 data->current_parent, spec.fid);
1536 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1539 if (is_editable && spec.fname == data->focused_fieldname)
1540 Environment->setFocus(e);
1543 e->setMultiLine(true);
1544 e->setWordWrap(true);
1545 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1548 evt.EventType = EET_KEY_INPUT_EVENT;
1549 evt.KeyInput.Key = KEY_END;
1550 evt.KeyInput.Char = 0;
1551 evt.KeyInput.Control = 0;
1552 evt.KeyInput.Shift = 0;
1553 evt.KeyInput.PressedDown = true;
1557 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1558 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1559 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1560 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1561 e->setDrawBackground(false);
1567 if (!spec.flabel.empty()) {
1568 int font_height = g_fontengine->getTextHeight();
1569 rect.UpperLeftCorner.Y -= font_height;
1570 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1571 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1572 rect, false, true, data->current_parent, 0);
1575 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1579 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1580 std::vector<std::string> &parts)
1582 std::string name = parts[0];
1583 std::string label = parts[1];
1584 std::string default_val = parts[2];
1586 core::rect<s32> rect;
1588 if (data->explicit_size)
1589 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1591 v2s32 pos = getElementBasePos(nullptr);
1592 pos.Y = (data->simple_field_count + 2) * 60;
1593 v2s32 size = DesiredRect.getSize();
1595 rect = core::rect<s32>(
1596 size.X / 2 - 150, pos.Y,
1597 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1602 default_val = m_form_src->resolveText(default_val);
1605 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1610 utf8_to_wide(unescape_string(default_val)),
1611 258 + m_fields.size(),
1616 createTextField(data, spec, rect, false);
1618 m_fields.push_back(spec);
1620 data->simple_field_count++;
1623 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1624 const std::string &type)
1626 std::vector<std::string> v_pos = split(parts[0],',');
1627 std::vector<std::string> v_geom = split(parts[1],',');
1628 std::string name = parts[2];
1629 std::string label = parts[3];
1630 std::string default_val = parts[4];
1632 MY_CHECKPOS(type,0);
1633 MY_CHECKGEOM(type,1);
1638 if (data->real_coordinates) {
1639 pos = getRealCoordinateBasePos(v_pos);
1640 geom = getRealCoordinateGeometry(v_geom);
1642 pos = getElementBasePos(&v_pos);
1645 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1647 if (type == "textarea")
1649 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1650 pos.Y += m_btn_height;
1654 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1655 pos.Y -= m_btn_height;
1656 geom.Y = m_btn_height*2;
1660 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1662 if(!data->explicit_size)
1663 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1666 default_val = m_form_src->resolveText(default_val);
1669 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1674 utf8_to_wide(unescape_string(default_val)),
1675 258 + m_fields.size(),
1680 createTextField(data, spec, rect, type == "textarea");
1682 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1683 // warning referring to field_close_on_enter[]!
1685 m_fields.push_back(spec);
1688 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1689 const std::string &type)
1691 std::vector<std::string> parts = split(element,';');
1693 if (parts.size() == 3 || parts.size() == 4) {
1694 parseSimpleField(data,parts);
1698 if ((parts.size() == 5) ||
1699 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1701 parseTextArea(data,parts,type);
1704 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1707 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1709 std::vector<std::string> parts = split(element, ';');
1711 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1712 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1716 std::vector<std::string> v_pos = split(parts[0], ',');
1717 std::vector<std::string> v_geom = split(parts[1], ',');
1718 std::string name = parts[2];
1719 std::string text = parts[3];
1721 MY_CHECKPOS("hypertext", 0);
1722 MY_CHECKGEOM("hypertext", 1);
1727 if (data->real_coordinates) {
1728 pos = getRealCoordinateBasePos(v_pos);
1729 geom = getRealCoordinateGeometry(v_geom);
1731 pos = getElementBasePos(&v_pos);
1734 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1735 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1736 pos.Y += m_btn_height;
1739 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1742 text = m_form_src->resolveText(text);
1746 utf8_to_wide(unescape_string(text)),
1748 258 + m_fields.size()
1751 spec.ftype = f_HyperText;
1752 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1753 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1756 m_fields.push_back(spec);
1759 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1761 std::vector<std::string> parts = split(element,';');
1763 if ((parts.size() == 2) ||
1764 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1766 std::vector<std::string> v_pos = split(parts[0],',');
1767 std::string text = parts[1];
1769 MY_CHECKPOS("label",0);
1771 if(!data->explicit_size)
1772 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1774 std::vector<std::string> lines = split(text, '\n');
1776 for (unsigned int i = 0; i != lines.size(); i++) {
1777 std::wstring wlabel_colors = translate_string(
1778 utf8_to_wide(unescape_string(lines[i])));
1779 // Without color escapes to get the font dimensions
1780 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1782 core::rect<s32> rect;
1784 if (data->real_coordinates) {
1785 // Lines are spaced at the distance of 1/2 imgsize.
1786 // This alows lines that line up with the new elements
1787 // easily without sacrificing good line distance. If
1788 // it was one whole imgsize, it would have too much
1790 v2s32 pos = getRealCoordinateBasePos(v_pos);
1792 // Labels are positioned by their center, not their top.
1793 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1795 rect = core::rect<s32>(
1797 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1801 // Lines are spaced at the nominal distance of
1802 // 2/5 inventory slot, even if the font doesn't
1803 // quite match that. This provides consistent
1804 // form layout, at the expense of sometimes
1805 // having sub-optimal spacing for the font.
1806 // We multiply by 2 and then divide by 5, rather
1807 // than multiply by 0.4, to get exact results
1808 // in the integer cases: 0.4 is not exactly
1809 // representable in binary floating point.
1811 v2s32 pos = getElementBasePos(nullptr);
1812 pos.X += stof(v_pos[0]) * spacing.X;
1813 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1815 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1817 rect = core::rect<s32>(
1818 pos.X, pos.Y - m_btn_height,
1819 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1820 pos.Y + m_btn_height);
1827 258 + m_fields.size(),
1830 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1831 spec.flabel.c_str(), rect, false, false, data->current_parent,
1833 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1835 auto style = getDefaultStyleForElement("label", spec.fname);
1836 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1837 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1839 m_fields.push_back(spec);
1841 // labels should let events through
1843 m_clickthrough_elements.push_back(e);
1848 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1849 << "'" << std::endl;
1852 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1854 std::vector<std::string> parts = split(element,';');
1856 if ((parts.size() == 2) ||
1857 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1859 std::vector<std::string> v_pos = split(parts[0],',');
1860 std::wstring text = unescape_translate(
1861 unescape_string(utf8_to_wide(parts[1])));
1863 MY_CHECKPOS("vertlabel",1);
1866 core::rect<s32> rect;
1868 if (data->real_coordinates) {
1869 pos = getRealCoordinateBasePos(v_pos);
1871 // Vertlabels are positioned by center, not left.
1872 pos.X -= imgsize.X / 2;
1874 // We use text.length + 1 because without it, the rect
1875 // isn't quite tall enough and cuts off the text.
1876 rect = core::rect<s32>(pos.X, pos.Y,
1878 pos.Y + font_line_height(m_font) *
1879 (text.length() + 1));
1882 pos = getElementBasePos(&v_pos);
1884 // As above, the length must be one longer. The width of
1885 // the rect (15 pixels) seems rather arbitrary, but
1886 // changing it might break something.
1887 rect = core::rect<s32>(
1888 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1890 font_line_height(m_font) *
1891 (text.length() + 1) +
1892 ((imgsize.Y/2) - m_btn_height));
1895 if(!data->explicit_size)
1896 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1900 for (wchar_t i : text) {
1909 258 + m_fields.size()
1911 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1912 rect, false, false, data->current_parent, spec.fid);
1913 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1915 auto style = getDefaultStyleForElement("vertlabel", spec.fname, "label");
1916 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1917 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1919 m_fields.push_back(spec);
1921 // vertlabels should let events through
1923 m_clickthrough_elements.push_back(e);
1926 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1929 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1930 const std::string &type)
1932 std::vector<std::string> parts = split(element,';');
1934 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1935 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1937 std::vector<std::string> v_pos = split(parts[0],',');
1938 std::vector<std::string> v_geom = split(parts[1],',');
1939 std::string image_name = parts[2];
1940 std::string name = parts[3];
1941 std::string label = parts[4];
1943 MY_CHECKPOS("imagebutton",0);
1944 MY_CHECKGEOM("imagebutton",1);
1946 std::string pressed_image_name;
1948 if (parts.size() >= 8) {
1949 pressed_image_name = parts[7];
1955 if (data->real_coordinates) {
1956 pos = getRealCoordinateBasePos(v_pos);
1957 geom = getRealCoordinateGeometry(v_geom);
1959 pos = getElementBasePos(&v_pos);
1960 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1961 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1964 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1967 if (!data->explicit_size)
1968 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1970 image_name = unescape_string(image_name);
1971 pressed_image_name = unescape_string(pressed_image_name);
1973 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1978 utf8_to_wide(image_name),
1979 258 + m_fields.size()
1981 spec.ftype = f_Button;
1982 if (type == "image_button_exit")
1983 spec.is_exit = true;
1985 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1986 data->current_parent, spec.fid, spec.flabel.c_str());
1988 if (spec.fname == data->focused_fieldname) {
1989 Environment->setFocus(e);
1992 auto style = getStyleForElement("image_button", spec.fname);
1994 // Override style properties with values specified directly in the element
1995 if (!image_name.empty())
1996 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1998 if (!pressed_image_name.empty())
1999 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
2001 if (parts.size() >= 7) {
2002 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
2003 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
2006 e->setStyles(style);
2007 e->setScaleImage(true);
2009 m_fields.push_back(spec);
2013 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2016 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2018 std::vector<std::string> parts = split(element, ';');
2020 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
2021 data->real_coordinates) || ((parts.size() > 6) &&
2022 (m_formspec_version > FORMSPEC_API_VERSION)))
2024 std::vector<std::string> v_pos = split(parts[0],',');
2026 // If we're using real coordinates, add an extra field for height.
2027 // Width is not here because tabs are the width of the text, and
2028 // there's no reason to change that.
2030 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2031 bool auto_width = true;
2032 if (parts.size() == 7) {
2035 v_geom = split(parts[1], ',');
2036 if (v_geom.size() == 1)
2037 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2042 std::string name = parts[i+1];
2043 std::vector<std::string> buttons = split(parts[i+2], ',');
2044 std::string str_index = parts[i+3];
2045 bool show_background = true;
2046 bool show_border = true;
2047 int tab_index = stoi(str_index) - 1;
2049 MY_CHECKPOS("tabheader", 0);
2051 if (parts.size() == 6 + i) {
2052 if (parts[4+i] == "true")
2053 show_background = false;
2054 if (parts[5+i] == "false")
2055 show_border = false;
2062 258 + m_fields.size()
2065 spec.ftype = f_TabHeader;
2070 if (data->real_coordinates) {
2071 pos = getRealCoordinateBasePos(v_pos);
2073 geom = getRealCoordinateGeometry(v_geom);
2074 // Set default height
2075 if (parts.size() <= 6)
2076 geom.Y = m_btn_height * 2;
2077 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2079 geom.X = DesiredRect.getWidth(); // Set automatic width
2081 MY_CHECKGEOM("tabheader", 1);
2083 v2f32 pos_f = pos_offset * spacing;
2084 pos_f.X += stof(v_pos[0]) * spacing.X;
2085 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2086 pos = v2s32(pos_f.X, pos_f.Y);
2088 geom.Y = m_btn_height * 2;
2089 geom.X = DesiredRect.getWidth();
2092 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2095 gui::IGUITabControl *e = Environment->addTabControl(rect,
2096 data->current_parent, show_background, show_border, spec.fid);
2097 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2098 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2099 e->setTabHeight(geom.Y);
2101 if (spec.fname == data->focused_fieldname) {
2102 Environment->setFocus(e);
2105 auto style = getDefaultStyleForElement("tabheader", name);
2106 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2108 for (const std::string &button : buttons) {
2109 auto tab = e->addTab(unescape_translate(unescape_string(
2110 utf8_to_wide(button))).c_str(), -1);
2111 if (style.isNotDefault(StyleSpec::BGCOLOR))
2112 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2114 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2117 if ((tab_index >= 0) &&
2118 (buttons.size() < INT_MAX) &&
2119 (tab_index < (int) buttons.size()))
2120 e->setActiveTab(tab_index);
2122 m_fields.push_back(spec);
2125 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2126 << element << "'" << std::endl;
2129 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2131 if (m_client == 0) {
2132 warningstream << "invalid use of item_image_button with m_client==0"
2137 std::vector<std::string> parts = split(element,';');
2139 if ((parts.size() == 5) ||
2140 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2142 std::vector<std::string> v_pos = split(parts[0],',');
2143 std::vector<std::string> v_geom = split(parts[1],',');
2144 std::string item_name = parts[2];
2145 std::string name = parts[3];
2146 std::string label = parts[4];
2148 label = unescape_string(label);
2149 item_name = unescape_string(item_name);
2151 MY_CHECKPOS("itemimagebutton",0);
2152 MY_CHECKGEOM("itemimagebutton",1);
2157 if (data->real_coordinates) {
2158 pos = getRealCoordinateBasePos(v_pos);
2159 geom = getRealCoordinateGeometry(v_geom);
2161 pos = getElementBasePos(&v_pos);
2162 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2163 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2166 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2168 if(!data->explicit_size)
2169 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2171 IItemDefManager *idef = m_client->idef();
2173 item.deSerialize(item_name, idef);
2176 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2177 m_default_tooltip_bgcolor,
2178 m_default_tooltip_color);
2180 // the spec for the button
2183 utf8_to_wide(label),
2184 utf8_to_wide(item_name),
2185 258 + m_fields.size(),
2189 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2190 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2191 item_name, m_client);
2193 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2194 e_btn->setStyles(style);
2196 if (spec_btn.fname == data->focused_fieldname) {
2197 Environment->setFocus(e_btn);
2200 spec_btn.ftype = f_Button;
2201 rect += data->basepos-padding;
2202 spec_btn.rect = rect;
2203 m_fields.push_back(spec_btn);
2206 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2209 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2211 std::vector<std::string> parts = split(element,';');
2213 if ((parts.size() == 3) ||
2214 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2216 std::vector<std::string> v_pos = split(parts[0],',');
2217 std::vector<std::string> v_geom = split(parts[1],',');
2219 MY_CHECKPOS("box",0);
2220 MY_CHECKGEOM("box",1);
2225 if (data->real_coordinates) {
2226 pos = getRealCoordinateBasePos(v_pos);
2227 geom = getRealCoordinateGeometry(v_geom);
2229 pos = getElementBasePos(&v_pos);
2230 geom.X = stof(v_geom[0]) * spacing.X;
2231 geom.Y = stof(v_geom[1]) * spacing.Y;
2234 video::SColor tmp_color;
2236 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2241 258 + m_fields.size(),
2246 core::rect<s32> rect(pos, pos + geom);
2248 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid,
2251 auto style = getDefaultStyleForElement("box", spec.fname);
2252 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2256 m_fields.push_back(spec);
2259 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2263 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2266 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2268 std::vector<std::string> parts = split(element,';');
2269 const u32 parameter_count = parts.size();
2271 if ((parameter_count > 2 && m_formspec_version < 3) ||
2272 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2273 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2274 << element << "'" << std::endl;
2279 if (parameter_count >= 1 && parts[0] != "")
2280 parseColorString(parts[0], m_bgcolor, false);
2283 if (parameter_count >= 2) {
2284 if (parts[1] == "both") {
2285 m_bgnonfullscreen = true;
2286 m_bgfullscreen = true;
2287 } else if (parts[1] == "neither") {
2288 m_bgnonfullscreen = false;
2289 m_bgfullscreen = false;
2290 } else if (parts[1] != "" || m_formspec_version < 3) {
2291 m_bgfullscreen = is_yes(parts[1]);
2292 m_bgnonfullscreen = !m_bgfullscreen;
2297 if (parameter_count >= 3 && parts[2] != "")
2298 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2301 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2303 std::vector<std::string> parts = split(element,';');
2305 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2306 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2308 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2309 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2311 if (parts.size() >= 3) {
2312 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2314 data->inventorylist_options.slotborder = true;
2317 if (parts.size() == 5) {
2318 video::SColor tmp_color;
2320 if (parseColorString(parts[3], tmp_color, false))
2321 m_default_tooltip_bgcolor = tmp_color;
2322 if (parseColorString(parts[4], tmp_color, false))
2323 m_default_tooltip_color = tmp_color;
2326 // update all already parsed inventorylists
2327 for (GUIInventoryList *e : m_inventorylists) {
2328 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2329 data->inventorylist_options.slotbg_h);
2330 e->setSlotBorders(data->inventorylist_options.slotborder,
2331 data->inventorylist_options.slotbordercolor);
2335 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2338 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2340 std::vector<std::string> parts = split(element,';');
2341 if (parts.size() < 2) {
2342 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2343 << element << "'" << std::endl;
2347 // Get mode and check size
2348 bool rect_mode = parts[0].find(',') != std::string::npos;
2349 size_t base_size = rect_mode ? 3 : 2;
2350 if (parts.size() != base_size && parts.size() != base_size + 2) {
2351 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2352 << element << "'" << std::endl;
2357 video::SColor bgcolor = m_default_tooltip_bgcolor;
2358 video::SColor color = m_default_tooltip_color;
2359 if (parts.size() == base_size + 2 &&
2360 (!parseColorString(parts[base_size], bgcolor, false) ||
2361 !parseColorString(parts[base_size + 1], color, false))) {
2362 errorstream << "Invalid color in tooltip element(" << parts.size()
2363 << "): '" << element << "'" << std::endl;
2367 // Make tooltip spec
2368 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2369 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2373 std::vector<std::string> v_pos = split(parts[0], ',');
2374 std::vector<std::string> v_geom = split(parts[1], ',');
2376 MY_CHECKPOS("tooltip", 0);
2377 MY_CHECKGEOM("tooltip", 1);
2382 if (data->real_coordinates) {
2383 pos = getRealCoordinateBasePos(v_pos);
2384 geom = getRealCoordinateGeometry(v_geom);
2386 pos = getElementBasePos(&v_pos);
2387 geom.X = stof(v_geom[0]) * spacing.X;
2388 geom.Y = stof(v_geom[1]) * spacing.Y;
2391 FieldSpec fieldspec(
2395 258 + m_fields.size()
2398 core::rect<s32> rect(pos, pos + geom);
2400 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2401 data->current_parent, fieldspec.fid, rect);
2403 // the element the rect tooltip is bound to should not block mouse-clicks
2404 e->setVisible(false);
2406 m_fields.push_back(fieldspec);
2407 m_tooltip_rects.emplace_back(e, spec);
2410 m_tooltips[parts[0]] = spec;
2414 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2420 std::vector<std::string> parts = split(data,'[');
2422 if (parts.size() < 2) {
2426 if (trim(parts[0]) != "formspec_version") {
2430 if (is_number(parts[1])) {
2431 m_formspec_version = mystoi(parts[1]);
2438 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2440 if (element.empty())
2443 std::vector<std::string> parts = split(element,'[');
2445 if (parts.size() < 2)
2448 std::string type = trim(parts[0]);
2449 std::string description = trim(parts[1]);
2451 if (type != "size" && type != "invsize")
2454 if (type == "invsize")
2455 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2457 parseSize(data, description);
2462 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2464 if (element.empty())
2467 std::vector<std::string> parts = split(element, '[');
2469 if (parts.size() != 2)
2472 std::string type = trim(parts[0]);
2473 std::string description = trim(parts[1]);
2475 if (type != "position")
2478 parsePosition(data, description);
2483 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2485 std::vector<std::string> parts = split(element, ',');
2487 if (parts.size() == 2) {
2488 data->offset.X = stof(parts[0]);
2489 data->offset.Y = stof(parts[1]);
2493 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2496 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2498 if (element.empty())
2501 std::vector<std::string> parts = split(element, '[');
2503 if (parts.size() != 2)
2506 std::string type = trim(parts[0]);
2507 std::string description = trim(parts[1]);
2509 if (type != "anchor")
2512 parseAnchor(data, description);
2517 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2519 std::vector<std::string> parts = split(element, ',');
2521 if (parts.size() == 2) {
2522 data->anchor.X = stof(parts[0]);
2523 data->anchor.Y = stof(parts[1]);
2527 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2528 << "'" << std::endl;
2531 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2533 std::vector<std::string> parts = split(element, ';');
2535 if (parts.size() < 2) {
2536 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2537 << "'" << std::endl;
2544 for (size_t i = 1; i < parts.size(); i++) {
2545 size_t equal_pos = parts[i].find('=');
2546 if (equal_pos == std::string::npos) {
2547 errorstream << "Invalid style element (Property missing value): '" << element
2548 << "'" << std::endl;
2552 std::string propname = trim(parts[i].substr(0, equal_pos));
2553 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2555 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2557 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2558 if (prop == StyleSpec::NONE) {
2559 if (property_warned.find(propname) != property_warned.end()) {
2560 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2562 << "'" << std::endl;
2563 property_warned.insert(propname);
2568 spec.set(prop, value);
2571 std::vector<std::string> selectors = split(parts[0], ',');
2572 for (size_t sel = 0; sel < selectors.size(); sel++) {
2573 std::string selector = trim(selectors[sel]);
2575 // Copy the style properties to a new StyleSpec
2576 // This allows a separate state mask per-selector
2577 StyleSpec selector_spec = spec;
2579 // Parse state information, if it exists
2580 bool state_valid = true;
2581 size_t state_pos = selector.find(':');
2582 if (state_pos != std::string::npos) {
2583 std::string state_str = selector.substr(state_pos + 1);
2584 selector = selector.substr(0, state_pos);
2586 if (state_str.empty()) {
2587 errorstream << "Invalid style element (Invalid state): '" << element
2588 << "'" << std::endl;
2589 state_valid = false;
2591 std::vector<std::string> states = split(state_str, '+');
2592 for (std::string &state : states) {
2593 StyleSpec::State converted = StyleSpec::getStateByName(state);
2594 if (converted == StyleSpec::STATE_INVALID) {
2595 infostream << "Unknown style state " << state <<
2596 " in element '" << element << "'" << std::endl;
2597 state_valid = false;
2601 selector_spec.addState(converted);
2607 // Skip this selector
2612 theme_by_type[selector].push_back(selector_spec);
2614 theme_by_name[selector].push_back(selector_spec);
2617 // Backwards-compatibility for existing _hovered/_pressed properties
2618 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2619 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2620 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2621 StyleSpec hover_spec;
2622 hover_spec.addState(StyleSpec::STATE_HOVERED);
2624 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2625 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2627 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2628 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2630 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2631 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2635 theme_by_type[selector].push_back(hover_spec);
2637 theme_by_name[selector].push_back(hover_spec);
2640 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2641 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2642 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2643 StyleSpec press_spec;
2644 press_spec.addState(StyleSpec::STATE_PRESSED);
2646 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2647 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2649 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2650 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2652 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2653 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2657 theme_by_type[selector].push_back(press_spec);
2659 theme_by_name[selector].push_back(press_spec);
2667 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2670 if (element.empty())
2673 if (parseVersionDirect(element))
2676 size_t pos = element.find('[');
2677 if (pos == std::string::npos)
2680 std::string type = trim(element.substr(0, pos));
2681 std::string description = element.substr(pos+1);
2683 if (type == "container") {
2684 parseContainer(data, description);
2688 if (type == "container_end") {
2689 parseContainerEnd(data);
2693 if (type == "list") {
2694 parseList(data, description);
2698 if (type == "listring") {
2699 parseListRing(data, description);
2703 if (type == "checkbox") {
2704 parseCheckbox(data, description);
2708 if (type == "image") {
2709 parseImage(data, description);
2713 if (type == "animated_image") {
2714 parseAnimatedImage(data, description);
2718 if (type == "item_image") {
2719 parseItemImage(data, description);
2723 if (type == "button" || type == "button_exit") {
2724 parseButton(data, description, type);
2728 if (type == "background" || type == "background9") {
2729 parseBackground(data, description);
2733 if (type == "tableoptions"){
2734 parseTableOptions(data,description);
2738 if (type == "tablecolumns"){
2739 parseTableColumns(data,description);
2743 if (type == "table"){
2744 parseTable(data,description);
2748 if (type == "textlist"){
2749 parseTextList(data,description);
2753 if (type == "dropdown"){
2754 parseDropDown(data,description);
2758 if (type == "field_close_on_enter") {
2759 parseFieldCloseOnEnter(data, description);
2763 if (type == "pwdfield") {
2764 parsePwdField(data,description);
2768 if ((type == "field") || (type == "textarea")){
2769 parseField(data,description,type);
2773 if (type == "hypertext") {
2774 parseHyperText(data,description);
2778 if (type == "label") {
2779 parseLabel(data,description);
2783 if (type == "vertlabel") {
2784 parseVertLabel(data,description);
2788 if (type == "item_image_button") {
2789 parseItemImageButton(data,description);
2793 if ((type == "image_button") || (type == "image_button_exit")) {
2794 parseImageButton(data,description,type);
2798 if (type == "tabheader") {
2799 parseTabHeader(data,description);
2803 if (type == "box") {
2804 parseBox(data,description);
2808 if (type == "bgcolor") {
2809 parseBackgroundColor(data,description);
2813 if (type == "listcolors") {
2814 parseListColors(data,description);
2818 if (type == "tooltip") {
2819 parseTooltip(data,description);
2823 if (type == "scrollbar") {
2824 parseScrollBar(data, description);
2828 if (type == "real_coordinates") {
2829 data->real_coordinates = is_yes(description);
2833 if (type == "style") {
2834 parseStyle(data, description, false);
2838 if (type == "style_type") {
2839 parseStyle(data, description, true);
2843 if (type == "scrollbaroptions") {
2844 parseScrollBarOptions(data, description);
2848 if (type == "scroll_container") {
2849 parseScrollContainer(data, description);
2853 if (type == "scroll_container_end") {
2854 parseScrollContainerEnd(data);
2859 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2863 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2865 /* useless to regenerate without a screensize */
2866 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2873 for (auto &m_table : m_tables) {
2874 std::string tablename = m_table.first.fname;
2875 GUITable *table = m_table.second;
2876 mydata.table_dyndata[tablename] = table->getDynamicData();
2880 if (!m_focused_element.empty())
2881 mydata.focused_fieldname = m_focused_element;
2884 gui::IGUIElement *focused_element = Environment->getFocus();
2885 if (focused_element && focused_element->getParent() == this) {
2886 s32 focused_id = focused_element->getID();
2887 if (focused_id > 257) {
2888 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2889 if (field.fid == focused_id) {
2890 mydata.focused_fieldname = field.fname;
2900 for (auto &table_it : m_tables)
2901 table_it.second->drop();
2902 for (auto &inventorylist_it : m_inventorylists)
2903 inventorylist_it->drop();
2904 for (auto &checkbox_it : m_checkboxes)
2905 checkbox_it.second->drop();
2906 for (auto &scrollbar_it : m_scrollbars)
2907 scrollbar_it.second->drop();
2908 for (auto &background_it : m_backgrounds)
2909 background_it->drop();
2910 for (auto &tooltip_rect_it : m_tooltip_rects)
2911 tooltip_rect_it.first->drop();
2912 for (auto &clickthrough_it : m_clickthrough_elements)
2913 clickthrough_it->drop();
2914 for (auto &scroll_container_it : m_scroll_containers)
2915 scroll_container_it.second->drop();
2917 mydata.size = v2s32(100, 100);
2918 mydata.screensize = screensize;
2919 mydata.offset = v2f32(0.5f, 0.5f);
2920 mydata.anchor = v2f32(0.5f, 0.5f);
2921 mydata.simple_field_count = 0;
2923 // Base position of contents of form
2924 mydata.basepos = getBasePos();
2926 // the parent for the parsed elements
2927 mydata.current_parent = this;
2929 m_inventorylists.clear();
2930 m_backgrounds.clear();
2932 m_checkboxes.clear();
2933 m_scrollbars.clear();
2936 m_tooltip_rects.clear();
2937 m_inventory_rings.clear();
2938 m_dropdowns.clear();
2939 m_scroll_containers.clear();
2940 theme_by_name.clear();
2941 theme_by_type.clear();
2942 m_clickthrough_elements.clear();
2944 m_bgnonfullscreen = true;
2945 m_bgfullscreen = false;
2947 m_formspec_version = 1;
2950 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2951 m_bgcolor = video::SColor(
2952 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2953 clamp_u8(myround(formspec_bgcolor.X)),
2954 clamp_u8(myround(formspec_bgcolor.Y)),
2955 clamp_u8(myround(formspec_bgcolor.Z))
2960 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2961 m_fullscreen_bgcolor = video::SColor(
2962 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2963 clamp_u8(myround(formspec_bgcolor.X)),
2964 clamp_u8(myround(formspec_bgcolor.Y)),
2965 clamp_u8(myround(formspec_bgcolor.Z))
2969 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2970 m_default_tooltip_color = video::SColor(255,255,255,255);
2974 assert(!m_tooltip_element);
2975 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2976 m_tooltip_element = gui::StaticText::add(Environment, L"",
2977 core::rect<s32>(0, 0, 110, 18));
2978 m_tooltip_element->enableOverrideColor(true);
2979 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2980 m_tooltip_element->setDrawBackground(true);
2981 m_tooltip_element->setDrawBorder(true);
2982 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2983 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2984 m_tooltip_element->setWordWrap(false);
2985 //we're not parent so no autograb for this one!
2986 m_tooltip_element->grab();
2989 std::vector<std::string> elements = split(m_formspec_string,']');
2992 /* try to read version from first element only */
2993 if (!elements.empty()) {
2994 if (parseVersionDirect(elements[0])) {
2999 /* we need size first in order to calculate image scale */
3000 mydata.explicit_size = false;
3001 for (; i< elements.size(); i++) {
3002 if (!parseSizeDirect(&mydata, elements[i])) {
3007 /* "position" element is always after "size" element if it used */
3008 for (; i< elements.size(); i++) {
3009 if (!parsePositionDirect(&mydata, elements[i])) {
3014 /* "anchor" element is always after "position" (or "size" element) if it used */
3015 for (; i< elements.size(); i++) {
3016 if (!parseAnchorDirect(&mydata, elements[i])) {
3021 /* "no_prepend" element is always after "position" (or "size" element) if it used */
3022 bool enable_prepends = true;
3023 for (; i < elements.size(); i++) {
3024 if (elements[i].empty())
3027 std::vector<std::string> parts = split(elements[i], '[');
3028 if (trim(parts[0]) == "no_prepend")
3029 enable_prepends = false;
3034 /* Copy of the "real_coordinates" element for after the form size. */
3035 mydata.real_coordinates = m_formspec_version >= 2;
3036 for (; i < elements.size(); i++) {
3037 std::vector<std::string> parts = split(elements[i], '[');
3038 std::string name = trim(parts[0]);
3039 if (name != "real_coordinates" || parts.size() != 2)
3040 break; // Invalid format
3042 mydata.real_coordinates = is_yes(trim(parts[1]));
3045 if (mydata.explicit_size) {
3046 // compute scaling for specified form size
3048 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3049 v2u32 delta = current_screensize - m_lockscreensize;
3051 if (current_screensize.Y > m_lockscreensize.Y)
3056 if (current_screensize.X > m_lockscreensize.X)
3061 offset = v2s32(delta.X,delta.Y);
3063 mydata.screensize = m_lockscreensize;
3065 offset = v2s32(0,0);
3068 double gui_scaling = g_settings->getFloat("gui_scaling");
3069 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3073 // In fixed-size mode, inventory image size
3074 // is 0.53 inch multiplied by the gui_scaling
3075 // config parameter. This magic size is chosen
3076 // to make the main menu (15.5 inventory images
3077 // wide, including border) just fit into the
3078 // default window (800 pixels wide) at 96 DPI
3079 // and default scaling (1.00).
3080 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3082 // In variable-size mode, we prefer to make the
3083 // inventory image size 1/15 of screen height,
3084 // multiplied by the gui_scaling config parameter.
3085 // If the preferred size won't fit the whole
3086 // form on the screen, either horizontally or
3087 // vertically, then we scale it down to fit.
3088 // (The magic numbers in the computation of what
3089 // fits arise from the scaling factors in the
3090 // following stanza, including the form border,
3091 // help text space, and 0.1 inventory slot spare.)
3092 // However, a minimum size is also set, that
3093 // the image size can't be less than 0.3 inch
3094 // multiplied by gui_scaling, even if this means
3095 // the form doesn't fit the screen.
3097 // For mobile devices these magic numbers are
3098 // different and forms should always use the
3099 // maximum screen space available.
3100 double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
3101 double fitx_imgsize = mydata.screensize.X /
3102 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
3103 double fity_imgsize = mydata.screensize.Y /
3104 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
3105 use_imgsize = MYMIN(prefer_imgsize,
3106 MYMIN(fitx_imgsize, fity_imgsize));
3108 double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
3109 double fitx_imgsize = mydata.screensize.X /
3110 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3111 double fity_imgsize = mydata.screensize.Y /
3112 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
3113 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3114 double min_imgsize = 0.3 * screen_dpi * gui_scaling;
3115 use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
3116 MYMIN(fitx_imgsize, fity_imgsize)));
3120 // Everything else is scaled in proportion to the
3121 // inventory image size. The inventory slot spacing
3122 // is 5/4 image size horizontally and 15/13 image size
3123 // vertically. The padding around the form (incorporating
3124 // the border of the outer inventory slots) is 3/8
3125 // image size. Font height (baseline to baseline)
3126 // is 2/5 vertical inventory slot spacing, and button
3127 // half-height is 7/8 of font height.
3128 imgsize = v2s32(use_imgsize, use_imgsize);
3129 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3130 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3131 m_btn_height = use_imgsize*15.0/13 * 0.35;
3133 m_font = g_fontengine->getFont();
3135 if (mydata.real_coordinates) {
3136 mydata.size = v2s32(
3137 mydata.invsize.X*imgsize.X,
3138 mydata.invsize.Y*imgsize.Y
3141 mydata.size = v2s32(
3142 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3143 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3147 DesiredRect = mydata.rect = core::rect<s32>(
3148 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3149 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3150 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3151 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3154 // Non-size[] form must consist only of text fields and
3155 // implicit "Proceed" button. Use default font, and
3156 // temporary form size which will be recalculated below.
3157 m_font = g_fontengine->getFont();
3158 m_btn_height = font_line_height(m_font) * 0.875;
3159 DesiredRect = core::rect<s32>(
3160 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3161 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3162 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3163 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3166 recalculateAbsolutePosition(false);
3167 mydata.basepos = getBasePos();
3168 m_tooltip_element->setOverrideFont(m_font);
3170 gui::IGUISkin *skin = Environment->getSkin();
3172 gui::IGUIFont *old_font = skin->getFont();
3173 skin->setFont(m_font);
3175 pos_offset = v2f32();
3177 // used for formspec versions < 3
3178 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3180 if (enable_prepends) {
3181 // Backup the coordinates so that prepends can use the coordinates of choice.
3182 bool rc_backup = mydata.real_coordinates;
3183 u16 version_backup = m_formspec_version;
3184 mydata.real_coordinates = false; // Old coordinates by default.
3186 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3187 for (const auto &element : prepend_elements)
3188 parseElement(&mydata, element);
3190 // legacy sorting for formspec versions < 3
3191 if (m_formspec_version >= 3)
3192 // prepends do not need to be reordered
3193 legacy_sort_start = Children.getLast();
3194 else if (version_backup >= 3)
3195 // only prepends elements have to be reordered
3196 legacySortElements(legacy_sort_start);
3198 m_formspec_version = version_backup;
3199 mydata.real_coordinates = rc_backup; // Restore coordinates
3202 for (; i< elements.size(); i++) {
3203 parseElement(&mydata, elements[i]);
3206 if (mydata.current_parent != this) {
3207 errorstream << "Invalid formspec string: scroll_container was never closed!"
3209 } else if (!container_stack.empty()) {
3210 errorstream << "Invalid formspec string: container was never closed!"
3214 // get the scrollbar elements for scroll_containers
3215 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3216 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3217 if (c.first == b.first.fname) {
3218 c.second->setScrollBar(b.second);
3224 // If there are fields without explicit size[], add a "Proceed"
3225 // button and adjust size to fit all the fields.
3226 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3227 mydata.rect = core::rect<s32>(
3228 mydata.screensize.X / 2 - 580 / 2,
3229 mydata.screensize.Y / 2 - 300 / 2,
3230 mydata.screensize.X / 2 + 580 / 2,
3231 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3234 DesiredRect = mydata.rect;
3235 recalculateAbsolutePosition(false);
3236 mydata.basepos = getBasePos();
3239 v2s32 pos = mydata.basepos;
3240 pos.Y = (mydata.simple_field_count + 2) * 60;
3242 v2s32 size = DesiredRect.getSize();
3243 mydata.rect = core::rect<s32>(
3244 size.X / 2 - 70, pos.Y,
3245 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3247 const wchar_t *text = wgettext("Proceed");
3248 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3253 //set initial focus if parser didn't set it
3254 focused_element = Environment->getFocus();
3255 if (!focused_element
3256 || !isMyChild(focused_element)
3257 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3260 skin->setFont(old_font);
3263 if (m_formspec_version < 3)
3264 legacySortElements(legacy_sort_start);
3267 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3270 Draw order for formspec_version <= 2:
3274 0 All other elements
3276 2 item_image, item_image_button
3281 if (from == Children.end())
3282 from = Children.begin();
3286 core::list<IGUIElement *>::Iterator to = Children.end();
3287 // 1: Copy into a sortable container
3288 std::vector<IGUIElement *> elements;
3289 for (auto it = from; it != to; ++it)
3290 elements.emplace_back(*it);
3292 // 2: Sort the container
3293 std::stable_sort(elements.begin(), elements.end(),
3294 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3295 const FieldSpec *spec_a = getSpecByID(a->getID());
3296 const FieldSpec *spec_b = getSpecByID(b->getID());
3297 return spec_a && spec_b &&
3298 spec_a->priority < spec_b->priority;
3301 // 3: Re-assign the pointers
3302 for (auto e : elements) {
3309 bool GUIFormSpecMenu::getAndroidUIInput()
3311 if (!hasAndroidUIInput())
3315 if (porting::getInputDialogState() == -1)
3318 std::string fieldname = m_jni_field_name;
3319 m_jni_field_name.clear();
3321 for (const FieldSpec &field : m_fields) {
3322 if (field.fname != fieldname)
3325 IGUIElement *element = getElementFromId(field.fid, true);
3327 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3330 std::string text = porting::getInputDialogValue();
3331 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3337 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3339 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3341 for (const GUIInventoryList *e : m_inventorylists) {
3342 s32 item_index = e->getItemIndexAtPos(p);
3343 if (item_index != -1)
3344 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3348 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3351 void GUIFormSpecMenu::drawSelectedItem()
3353 video::IVideoDriver* driver = Environment->getVideoDriver();
3355 if (!m_selected_item) {
3356 // reset rotation time
3357 drawItemStack(driver, m_font, ItemStack(),
3358 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3359 m_client, IT_ROT_DRAGGED);
3363 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3365 InventoryList *list = inv->getList(m_selected_item->listname);
3367 ItemStack stack = list->getItem(m_selected_item->i);
3368 stack.count = m_selected_amount;
3370 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3371 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3372 rect.constrainTo(driver->getViewPort());
3373 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3376 void GUIFormSpecMenu::drawMenu()
3379 const std::string &newform = m_form_src->getForm();
3380 if (newform != m_formspec_string) {
3381 m_formspec_string = newform;
3382 regenerateGui(m_screensize_old);
3386 gui::IGUISkin* skin = Environment->getSkin();
3387 sanity_check(skin != NULL);
3388 gui::IGUIFont *old_font = skin->getFont();
3389 skin->setFont(m_font);
3391 m_hovered_item_tooltips.clear();
3393 updateSelectedItem();
3395 video::IVideoDriver* driver = Environment->getVideoDriver();
3398 Draw background color
3400 v2u32 screenSize = driver->getScreenSize();
3401 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3404 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3405 if (m_bgnonfullscreen)
3406 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3409 Draw rect_mode tooltip
3411 m_tooltip_element->setVisible(false);
3413 for (const auto &pair : m_tooltip_rects) {
3414 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3415 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3416 const std::wstring &text = pair.second.tooltip;
3417 if (!text.empty()) {
3418 showTooltip(text, pair.second.color, pair.second.bgcolor);
3427 for (gui::IGUIElement *e : m_backgrounds) {
3428 e->setVisible(true);
3430 e->setVisible(false);
3433 // Some elements are only visible while being drawn
3434 for (gui::IGUIElement *e : m_clickthrough_elements)
3435 e->setVisible(true);
3439 (This is where all the drawing happens.)
3441 gui::IGUIElement::draw();
3443 for (gui::IGUIElement *e : m_clickthrough_elements)
3444 e->setVisible(false);
3446 // Draw hovered item tooltips
3447 for (const std::string &tooltip : m_hovered_item_tooltips) {
3448 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3449 m_default_tooltip_bgcolor);
3452 if (m_hovered_item_tooltips.empty()) {
3453 // reset rotation time
3454 drawItemStack(driver, m_font, ItemStack(),
3455 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3456 NULL, m_client, IT_ROT_HOVERED);
3459 /* TODO find way to show tooltips on touchscreen */
3460 #ifndef HAVE_TOUCHSCREENGUI
3461 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3465 Draw fields/buttons tooltips and update the mouse cursor
3467 gui::IGUIElement *hovered =
3468 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3470 #ifndef HAVE_TOUCHSCREENGUI
3471 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3473 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3475 bool hovered_element_found = false;
3477 if (hovered != NULL) {
3479 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3480 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3483 s32 id = hovered->getID();
3486 m_old_tooltip_id = id;
3488 if (id == m_old_tooltip_id) {
3489 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3491 m_hovered_time = porting::getTimeMs();
3492 m_old_tooltip_id = id;
3496 // Find and update the current tooltip and cursor icon
3498 for (const FieldSpec &field : m_fields) {
3500 if (field.fid != id)
3503 if (delta >= m_tooltip_show_delay) {
3504 const std::wstring &text = m_tooltips[field.fname].tooltip;
3506 showTooltip(text, m_tooltips[field.fname].color,
3507 m_tooltips[field.fname].bgcolor);
3510 #ifndef HAVE_TOUCHSCREENGUI
3511 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3512 current_cursor_icon != field.fcursor_icon)
3513 cursor_control->setActiveIcon(field.fcursor_icon);
3516 hovered_element_found = true;
3523 if (!hovered_element_found) {
3524 // no element is hovered
3525 #ifndef HAVE_TOUCHSCREENGUI
3526 if (current_cursor_icon != ECI_NORMAL)
3527 cursor_control->setActiveIcon(ECI_NORMAL);
3531 m_tooltip_element->draw();
3534 Draw dragged item stack
3538 skin->setFont(old_font);
3542 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3543 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3545 EnrichedString ntext(text);
3546 ntext.setDefaultColor(color);
3547 ntext.setBackground(bgcolor);
3549 setStaticText(m_tooltip_element, ntext);
3551 // Tooltip size and offset
3552 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3553 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3555 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3556 int tooltip_offset_x = m_btn_height;
3557 int tooltip_offset_y = m_btn_height;
3559 tooltip_offset_x *= 3;
3560 tooltip_offset_y = 0;
3561 if (m_pointer.X > (s32)screenSize.X / 2)
3562 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3565 // Calculate and set the tooltip position
3566 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3567 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3568 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3569 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3570 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3571 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3573 m_tooltip_element->setRelativePosition(
3575 core::position2d<s32>(tooltip_x, tooltip_y),
3576 core::dimension2d<s32>(tooltip_width, tooltip_height)
3580 // Display the tooltip
3581 m_tooltip_element->setVisible(true);
3582 bringToFront(m_tooltip_element);
3585 void GUIFormSpecMenu::updateSelectedItem()
3587 verifySelectedItem();
3589 // If craftresult is nonempty and nothing else is selected, select it now.
3590 if (!m_selected_item) {
3591 for (const GUIInventoryList *e : m_inventorylists) {
3592 if (e->getListname() != "craftpreview")
3595 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3599 InventoryList *list = inv->getList("craftresult");
3601 if (!list || list->getSize() == 0)
3604 const ItemStack &item = list->getItem(0);
3608 // Grab selected item from the crafting result list
3609 m_selected_item = new GUIInventoryList::ItemSpec;
3610 m_selected_item->inventoryloc = e->getInventoryloc();
3611 m_selected_item->listname = "craftresult";
3612 m_selected_item->i = 0;
3613 m_selected_amount = item.count;
3614 m_selected_dragging = false;
3619 // If craftresult is selected, keep the whole stack selected
3620 if (m_selected_item && m_selected_item->listname == "craftresult")
3621 m_selected_amount = verifySelectedItem().count;
3624 ItemStack GUIFormSpecMenu::verifySelectedItem()
3626 // If the selected stack has become empty for some reason, deselect it.
3627 // If the selected stack has become inaccessible, deselect it.
3628 // If the selected stack has become smaller, adjust m_selected_amount.
3629 // Return the selected stack.
3631 if (m_selected_item) {
3632 if (m_selected_item->isValid()) {
3633 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3635 InventoryList *list = inv->getList(m_selected_item->listname);
3636 if (list && (u32) m_selected_item->i < list->getSize()) {
3637 ItemStack stack = list->getItem(m_selected_item->i);
3638 if (!m_selected_swap.empty()) {
3639 if (m_selected_swap.name == stack.name &&
3640 m_selected_swap.count == stack.count)
3641 m_selected_swap.clear();
3643 m_selected_amount = std::min(m_selected_amount, stack.count);
3652 // selection was not valid
3653 delete m_selected_item;
3654 m_selected_item = nullptr;
3655 m_selected_amount = 0;
3656 m_selected_dragging = false;
3661 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3667 if (quitmode == quit_mode_accept) {
3668 fields["quit"] = "true";
3671 if (quitmode == quit_mode_cancel) {
3672 fields["quit"] = "true";
3673 m_text_dst->gotText(fields);
3677 if (current_keys_pending.key_down) {
3678 fields["key_down"] = "true";
3679 current_keys_pending.key_down = false;
3682 if (current_keys_pending.key_up) {
3683 fields["key_up"] = "true";
3684 current_keys_pending.key_up = false;
3687 if (current_keys_pending.key_enter) {
3688 fields["key_enter"] = "true";
3689 current_keys_pending.key_enter = false;
3692 if (!current_field_enter_pending.empty()) {
3693 fields["key_enter_field"] = current_field_enter_pending;
3694 current_field_enter_pending = "";
3697 if (current_keys_pending.key_escape) {
3698 fields["key_escape"] = "true";
3699 current_keys_pending.key_escape = false;
3702 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3704 std::string name = s.fname;
3705 if (s.ftype == f_Button) {
3706 fields[name] = wide_to_utf8(s.flabel);
3707 } else if (s.ftype == f_Table) {
3708 GUITable *table = getTable(s.fname);
3710 fields[name] = table->checkEvent();
3712 } else if (s.ftype == f_DropDown) {
3713 // No dynamic cast possible due to some distributions shipped
3714 // without rtti support in Irrlicht
3715 IGUIElement *element = getElementFromId(s.fid, true);
3716 gui::IGUIComboBox *e = NULL;
3717 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3718 e = static_cast<gui::IGUIComboBox *>(element);
3720 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3721 << "field without dropdown element" << std::endl;
3724 s32 selected = e->getSelected();
3725 if (selected >= 0) {
3726 std::vector<std::string> *dropdown_values =
3727 getDropDownValues(s.fname);
3728 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3729 fields[name] = (*dropdown_values)[selected];
3732 } else if (s.ftype == f_TabHeader) {
3733 // No dynamic cast possible due to some distributions shipped
3734 // without rtti support in Irrlicht
3735 IGUIElement *element = getElementFromId(s.fid, true);
3736 gui::IGUITabControl *e = nullptr;
3737 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3738 e = static_cast<gui::IGUITabControl *>(element);
3742 std::stringstream ss;
3743 ss << (e->getActiveTab() +1);
3744 fields[name] = ss.str();
3746 } else if (s.ftype == f_CheckBox) {
3747 // No dynamic cast possible due to some distributions shipped
3748 // without rtti support in Irrlicht
3749 IGUIElement *element = getElementFromId(s.fid, true);
3750 gui::IGUICheckBox *e = nullptr;
3751 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3752 e = static_cast<gui::IGUICheckBox*>(element);
3757 fields[name] = "true";
3759 fields[name] = "false";
3761 } else if (s.ftype == f_ScrollBar) {
3762 // No dynamic cast possible due to some distributions shipped
3763 // without rtti support in Irrlicht
3764 IGUIElement *element = getElementFromId(s.fid, true);
3765 GUIScrollBar *e = nullptr;
3766 if (element && element->getType() == gui::EGUIET_ELEMENT)
3767 e = static_cast<GUIScrollBar *>(element);
3770 std::stringstream os;
3772 if (s.fdefault == L"Changed")
3773 fields[name] = "CHG:" + os.str();
3775 fields[name] = "VAL:" + os.str();
3777 } else if (s.ftype == f_AnimatedImage) {
3778 // No dynamic cast possible due to some distributions shipped
3779 // without rtti support in Irrlicht
3780 IGUIElement *element = getElementFromId(s.fid, true);
3781 GUIAnimatedImage *e = nullptr;
3782 if (element && element->getType() == gui::EGUIET_ELEMENT)
3783 e = static_cast<GUIAnimatedImage *>(element);
3786 fields[name] = std::to_string(e->getFrameIndex() + 1);
3788 IGUIElement *e = getElementFromId(s.fid, true);
3790 fields[name] = wide_to_utf8(e->getText());
3795 m_text_dst->gotText(fields);
3799 static bool isChild(gui::IGUIElement *tocheck, gui::IGUIElement *parent)
3802 if (tocheck == parent) {
3805 tocheck = tocheck->getParent();
3810 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3812 // The IGUITabControl renders visually using the skin's selected
3813 // font, which we override for the duration of form drawing,
3814 // but computes tab hotspots based on how it would have rendered
3815 // using the font that is selected at the time of button release.
3816 // To make these two consistent, temporarily override the skin's
3817 // font while the IGUITabControl is processing the event.
3818 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3819 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3820 s32 x = event.MouseInput.X;
3821 s32 y = event.MouseInput.Y;
3822 gui::IGUIElement *hovered =
3823 Environment->getRootGUIElement()->getElementFromPoint(
3824 core::position2d<s32>(x, y));
3825 if (hovered && isMyChild(hovered) &&
3826 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3827 gui::IGUISkin* skin = Environment->getSkin();
3828 sanity_check(skin != NULL);
3829 gui::IGUIFont *old_font = skin->getFont();
3830 skin->setFont(m_font);
3831 bool retval = hovered->OnEvent(event);
3832 skin->setFont(old_font);
3837 // Fix Esc/Return key being eaten by checkboxen and tables
3838 if (event.EventType == EET_KEY_INPUT_EVENT) {
3839 KeyPress kp(event.KeyInput);
3840 if (kp == EscapeKey || kp == CancelKey
3841 || kp == getKeySetting("keymap_inventory")
3842 || event.KeyInput.Key==KEY_RETURN) {
3843 gui::IGUIElement *focused = Environment->getFocus();
3844 if (focused && isMyChild(focused) &&
3845 (focused->getType() == gui::EGUIET_LIST_BOX ||
3846 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3847 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3848 event.KeyInput.Key != KEY_RETURN)) {
3854 // Mouse wheel and move events: send to hovered element instead of focused
3855 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3856 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3857 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3858 event.MouseInput.ButtonStates == 0))) {
3859 s32 x = event.MouseInput.X;
3860 s32 y = event.MouseInput.Y;
3861 gui::IGUIElement *hovered =
3862 Environment->getRootGUIElement()->getElementFromPoint(
3863 core::position2d<s32>(x, y));
3864 if (hovered && isMyChild(hovered)) {
3865 hovered->OnEvent(event);
3866 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3870 if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3871 s32 x = event.MouseInput.X;
3872 s32 y = event.MouseInput.Y;
3873 gui::IGUIElement *hovered =
3874 Environment->getRootGUIElement()->getElementFromPoint(
3875 core::position2d<s32>(x, y));
3876 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3877 m_old_tooltip_id = -1;
3879 if (!isChild(hovered, this)) {
3880 if (DoubleClickDetection(event)) {
3886 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3887 /* TODO add a check like:
3888 if (event.JoystickEvent != joystick_we_listen_for)
3891 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3893 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3895 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3897 acceptInput(quit_mode_accept);
3905 return GUIModalMenu::preprocessEvent(event);
3908 /******************************************************************************/
3909 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3911 /* The following code is for capturing double-clicks of the mouse button
3912 * and translating the double-click into an EET_KEY_INPUT_EVENT event
3913 * -- which closes the form -- under some circumstances.
3915 * There have been many github issues reporting this as a bug even though it
3916 * was an intended feature. For this reason, remapping the double-click as
3917 * an ESC must be explicitly set when creating this class via the
3918 * /p remap_dbl_click parameter of the constructor.
3921 if (!m_remap_dbl_click)
3924 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3925 m_doubleclickdetect[0].pos = m_doubleclickdetect[1].pos;
3926 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3928 m_doubleclickdetect[1].pos = m_pointer;
3929 m_doubleclickdetect[1].time = porting::getTimeMs();
3931 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3932 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3937 double squaredistance =
3938 m_doubleclickdetect[0].pos
3939 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3941 if (squaredistance > (30*30)) {
3945 SEvent* translated = new SEvent();
3946 assert(translated != 0);
3947 //translate doubleclick to escape
3948 memset(translated, 0, sizeof(SEvent));
3949 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3950 translated->KeyInput.Key = KEY_ESCAPE;
3951 translated->KeyInput.Control = false;
3952 translated->KeyInput.Shift = false;
3953 translated->KeyInput.PressedDown = true;
3954 translated->KeyInput.Char = 0;
3955 OnEvent(*translated);
3957 // no need to send the key up event as we're already deleted
3958 // and no one else did notice this event
3966 void GUIFormSpecMenu::tryClose()
3970 acceptInput(quit_mode_cancel);
3973 m_text_dst->gotText(L"MenuQuit");
3977 enum ButtonEventType : u8
3990 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3992 if (event.EventType==EET_KEY_INPUT_EVENT) {
3993 KeyPress kp(event.KeyInput);
3994 if (event.KeyInput.PressedDown && (
3995 (kp == EscapeKey) || (kp == CancelKey) ||
3996 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4001 if (m_client != NULL && event.KeyInput.PressedDown &&
4002 (kp == getKeySetting("keymap_screenshot"))) {
4003 m_client->makeScreenshot();
4006 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4007 m_show_debug = !m_show_debug;
4009 if (event.KeyInput.PressedDown &&
4010 (event.KeyInput.Key==KEY_RETURN ||
4011 event.KeyInput.Key==KEY_UP ||
4012 event.KeyInput.Key==KEY_DOWN)
4014 switch (event.KeyInput.Key) {
4016 current_keys_pending.key_enter = true;
4019 current_keys_pending.key_up = true;
4022 current_keys_pending.key_down = true;
4026 //can't happen at all!
4027 FATAL_ERROR("Reached a source line that can't ever been reached");
4030 if (current_keys_pending.key_enter && m_allowclose) {
4031 acceptInput(quit_mode_accept);
4041 /* Mouse event other than movement, or crossing the border of inventory
4042 field while holding right mouse button
4044 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4045 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4046 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4047 event.MouseInput.isRightPressed() &&
4048 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4050 // Get selected item and hovered/clicked item (s)
4052 m_old_tooltip_id = -1;
4053 updateSelectedItem();
4054 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4056 Inventory *inv_selected = NULL;
4057 Inventory *inv_s = NULL;
4058 InventoryList *list_s = NULL;
4060 if (m_selected_item) {
4061 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4062 sanity_check(inv_selected);
4063 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4070 inv_s = m_invmgr->getInventory(s.inventoryloc);
4073 errorstream << "InventoryMenu: The selected inventory location "
4074 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4076 s.i = -1; // make it invalid again
4080 list_s = inv_s->getList(s.listname);
4081 if (list_s == NULL) {
4082 verbosestream << "InventoryMenu: The selected inventory list \""
4083 << s.listname << "\" does not exist" << std::endl;
4084 s.i = -1; // make it invalid again
4088 if ((u32)s.i >= list_s->getSize()) {
4089 infostream << "InventoryMenu: The selected inventory list \""
4090 << s.listname << "\" is too small (i=" << s.i << ", size="
4091 << list_s->getSize() << ")" << std::endl;
4092 s.i = -1; // make it invalid again
4096 s_count = list_s->getItem(s.i).count;
4099 bool identical = m_selected_item && s.isValid() &&
4100 (inv_selected == inv_s) &&
4101 (m_selected_item->listname == s.listname) &&
4102 (m_selected_item->i == s.i);
4104 ButtonEventType button = BET_LEFT;
4105 ButtonEventType updown = BET_OTHER;
4106 switch (event.MouseInput.Event) {
4107 case EMIE_LMOUSE_PRESSED_DOWN:
4108 button = BET_LEFT; updown = BET_DOWN;
4110 case EMIE_RMOUSE_PRESSED_DOWN:
4111 button = BET_RIGHT; updown = BET_DOWN;
4113 case EMIE_MMOUSE_PRESSED_DOWN:
4114 button = BET_MIDDLE; updown = BET_DOWN;
4116 case EMIE_MOUSE_WHEEL:
4117 button = (event.MouseInput.Wheel > 0) ?
4118 BET_WHEEL_UP : BET_WHEEL_DOWN;
4121 case EMIE_LMOUSE_LEFT_UP:
4122 button = BET_LEFT; updown = BET_UP;
4124 case EMIE_RMOUSE_LEFT_UP:
4125 button = BET_RIGHT; updown = BET_UP;
4127 case EMIE_MMOUSE_LEFT_UP:
4128 button = BET_MIDDLE; updown = BET_UP;
4130 case EMIE_MOUSE_MOVED:
4137 // Set this number to a positive value to generate a move action
4138 // from m_selected_item to s.
4139 u32 move_amount = 0;
4141 // Set this number to a positive value to generate a move action
4142 // from s to the next inventory ring.
4143 u32 shift_move_amount = 0;
4145 // Set this number to a positive value to generate a drop action
4146 // from m_selected_item.
4147 u32 drop_amount = 0;
4149 // Set this number to a positive value to generate a craft action at s.
4150 u32 craft_amount = 0;
4154 // Some mouse button has been pressed
4156 //infostream << "Mouse button " << button << " pressed at p=("
4157 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4160 m_selected_dragging = false;
4162 if (s.isValid() && s.listname == "craftpreview") {
4163 // Craft preview has been clicked: craft
4164 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4165 } else if (!m_selected_item) {
4166 if (s_count && button != BET_WHEEL_UP) {
4167 // Non-empty stack has been clicked: select or shift-move it
4168 m_selected_item = new GUIInventoryList::ItemSpec(s);
4171 if (button == BET_RIGHT)
4172 count = (s_count + 1) / 2;
4173 else if (button == BET_MIDDLE)
4174 count = MYMIN(s_count, 10);
4175 else if (button == BET_WHEEL_DOWN)
4180 if (!event.MouseInput.Shift) {
4181 // no shift: select item
4182 m_selected_amount = count;
4183 m_selected_dragging = button != BET_WHEEL_DOWN;
4184 m_auto_place = false;
4186 // shift pressed: move item, right click moves 1
4187 shift_move_amount = button == BET_RIGHT ? 1 : count;
4190 } else { // m_selected_item != NULL
4191 assert(m_selected_amount >= 1);
4194 // Clicked a slot: move
4195 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4197 else if (button == BET_MIDDLE)
4198 move_amount = MYMIN(m_selected_amount, 10);
4199 else if (button == BET_LEFT)
4200 move_amount = m_selected_amount;
4204 if (button == BET_WHEEL_DOWN) {
4205 if (m_selected_amount < s_count)
4206 ++m_selected_amount;
4208 if (move_amount >= m_selected_amount)
4209 m_selected_amount = 0;
4211 m_selected_amount -= move_amount;
4215 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4216 && button != BET_WHEEL_DOWN) {
4217 // Clicked outside of the window: drop
4218 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4220 else if (button == BET_MIDDLE)
4221 drop_amount = MYMIN(m_selected_amount, 10);
4223 drop_amount = m_selected_amount;
4228 // Some mouse button has been released
4230 //infostream<<"Mouse button "<<button<<" released at p=("
4231 // <<p.X<<","<<p.Y<<")"<<std::endl;
4233 if (m_selected_dragging && m_selected_item) {
4236 // Dragged to different slot: move all selected
4237 move_amount = m_selected_amount;
4239 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4240 // Dragged outside of window: drop all selected
4241 drop_amount = m_selected_amount;
4245 m_selected_dragging = false;
4246 // Keep track of whether the mouse button be released
4247 // One click is drag without dropping. Click + release
4248 // + click changes to drop item when moved mode
4249 if (m_selected_item)
4250 m_auto_place = true;
4253 // Mouse has been moved and rmb is down and mouse pointer just
4254 // entered a new inventory field (checked in the entry-if, this
4255 // is the only action here that is generated by mouse movement)
4256 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4258 // TODO: middle mouse to move 10 items might be handy
4260 // Only move an item if the destination slot is empty
4261 // or contains the same item type as what is going to be
4263 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4264 InventoryList *list_to = list_s;
4265 assert(list_from && list_to);
4266 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4267 ItemStack stack_to = list_to->getItem(s.i);
4268 if (stack_to.empty() || stack_to.name == stack_from.name)
4277 // Possibly send inventory action to server
4278 if (move_amount > 0) {
4279 // Send IAction::Move
4281 assert(m_selected_item && m_selected_item->isValid());
4282 assert(s.isValid());
4284 assert(inv_selected && inv_s);
4285 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4286 InventoryList *list_to = list_s;
4287 assert(list_from && list_to);
4288 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4289 ItemStack stack_to = list_to->getItem(s.i);
4291 // Check how many items can be moved
4292 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4293 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4295 // If source stack cannot be added to destination stack at all,
4297 if (leftover.count == stack_from.count &&
4298 leftover.name == stack_from.name) {
4300 if (m_selected_swap.empty()) {
4301 m_selected_amount = stack_to.count;
4302 m_selected_dragging = false;
4304 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4305 // Skip next validation checks due async inventory calls
4306 m_selected_swap = stack_to;
4311 // Source stack goes fully into destination stack
4312 else if (leftover.empty()) {
4313 m_selected_amount -= move_amount;
4315 // Source stack goes partly into destination stack
4317 move_amount -= leftover.count;
4318 m_selected_amount -= move_amount;
4322 infostream << "Handing IAction::Move to manager" << std::endl;
4323 IMoveAction *a = new IMoveAction();
4324 a->count = move_amount;
4325 a->from_inv = m_selected_item->inventoryloc;
4326 a->from_list = m_selected_item->listname;
4327 a->from_i = m_selected_item->i;
4328 a->to_inv = s.inventoryloc;
4329 a->to_list = s.listname;
4331 m_invmgr->inventoryAction(a);
4333 } else if (shift_move_amount > 0) {
4334 u32 mis = m_inventory_rings.size();
4336 for (; i < mis; i++) {
4337 const ListRingSpec &sp = m_inventory_rings[i];
4338 if (sp.inventoryloc == s.inventoryloc
4339 && sp.listname == s.listname)
4343 if (i >= mis) // if not found
4345 u32 to_inv_ind = (i + 1) % mis;
4346 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4347 InventoryList *list_from = list_s;
4350 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4353 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4356 ItemStack stack_from = list_from->getItem(s.i);
4357 assert(shift_move_amount <= stack_from.count);
4359 infostream << "Handing IAction::Move to manager" << std::endl;
4360 IMoveAction *a = new IMoveAction();
4361 a->count = shift_move_amount;
4362 a->from_inv = s.inventoryloc;
4363 a->from_list = s.listname;
4365 a->to_inv = to_inv_sp.inventoryloc;
4366 a->to_list = to_inv_sp.listname;
4367 a->move_somewhere = true;
4368 m_invmgr->inventoryAction(a);
4370 } else if (drop_amount > 0) {
4371 // Send IAction::Drop
4373 assert(m_selected_item && m_selected_item->isValid());
4374 assert(inv_selected);
4375 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4377 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4379 // Check how many items can be dropped
4380 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4381 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4382 m_selected_amount -= drop_amount;
4384 infostream << "Handing IAction::Drop to manager" << std::endl;
4385 IDropAction *a = new IDropAction();
4386 a->count = drop_amount;
4387 a->from_inv = m_selected_item->inventoryloc;
4388 a->from_list = m_selected_item->listname;
4389 a->from_i = m_selected_item->i;
4390 m_invmgr->inventoryAction(a);
4391 } else if (craft_amount > 0) {
4392 assert(s.isValid());
4394 // if there are no items selected or the selected item
4395 // belongs to craftresult list, proceed with crafting
4396 if (!m_selected_item ||
4397 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4401 // Send IACTION_CRAFT
4402 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4403 ICraftAction *a = new ICraftAction();
4404 a->count = craft_amount;
4405 a->craft_inv = s.inventoryloc;
4406 m_invmgr->inventoryAction(a);
4410 // If m_selected_amount has been decreased to zero, deselect
4411 if (m_selected_amount == 0) {
4412 m_selected_swap.clear();
4413 delete m_selected_item;
4414 m_selected_item = nullptr;
4415 m_selected_amount = 0;
4416 m_selected_dragging = false;
4418 m_old_pointer = m_pointer;
4421 if (event.EventType == EET_GUI_EVENT) {
4422 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4424 // find the element that was clicked
4425 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4426 if ((s.ftype == f_TabHeader) &&
4427 (s.fid == event.GUIEvent.Caller->getID())) {
4435 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4437 if (!canTakeFocus(event.GUIEvent.Element)) {
4438 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4440 // Returning true disables focus change
4444 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4445 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4446 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4447 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4448 s32 caller_id = event.GUIEvent.Caller->getID();
4450 if (caller_id == 257) {
4452 acceptInput(quit_mode_accept);
4456 m_text_dst->gotText(L"ExitButton");
4458 // quitMenu deallocates menu
4462 // find the element that was clicked
4463 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4464 // if its a button, set the send field so
4465 // lua knows which button was pressed
4467 if (caller_id != s.fid)
4470 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4474 acceptInput(quit_mode_accept);
4477 m_text_dst->gotText(L"ExitButton");
4482 acceptInput(quit_mode_no);
4486 } else if (s.ftype == f_DropDown) {
4487 // only send the changed dropdown
4488 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4489 if (s2.ftype == f_DropDown) {
4494 acceptInput(quit_mode_no);
4496 // revert configuration to make sure dropdowns are sent on
4497 // regular button click
4498 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4499 if (s2.ftype == f_DropDown) {
4504 } else if (s.ftype == f_ScrollBar) {
4505 s.fdefault = L"Changed";
4506 acceptInput(quit_mode_no);
4508 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4516 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4517 // move scroll_containers
4518 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4519 c.second->onScrollEvent(event.GUIEvent.Caller);
4522 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4523 if (event.GUIEvent.Caller->getID() > 257) {
4524 bool close_on_enter = true;
4525 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4526 if (s.ftype == f_Unknown &&
4527 s.fid == event.GUIEvent.Caller->getID()) {
4528 current_field_enter_pending = s.fname;
4529 std::unordered_map<std::string, bool>::const_iterator it =
4530 field_close_on_enter.find(s.fname);
4531 if (it != field_close_on_enter.end())
4532 close_on_enter = (*it).second;
4538 if (m_allowclose && close_on_enter) {
4539 current_keys_pending.key_enter = true;
4540 acceptInput(quit_mode_accept);
4543 current_keys_pending.key_enter = true;
4546 // quitMenu deallocates menu
4551 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4552 int current_id = event.GUIEvent.Caller->getID();
4553 if (current_id > 257) {
4554 // find the element that was clicked
4555 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4556 // if it's a table, set the send field
4557 // so lua knows which table was changed
4558 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4569 return Parent ? Parent->OnEvent(event) : false;
4573 * get name of element by element id
4574 * @param id of element
4575 * @return name string or empty string
4577 std::string GUIFormSpecMenu::getNameByID(s32 id)
4579 for (FieldSpec &spec : m_fields) {
4587 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4589 for (FieldSpec &spec : m_fields) {
4597 * get label of element by id
4598 * @param id of element
4599 * @return label string or empty string
4601 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4603 for (FieldSpec &spec : m_fields) {
4610 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4611 const std::string &name, const std::string &parent_type) {
4612 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4615 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4616 const std::string &type, const std::string &name, const std::string &parent_type)
4618 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4620 auto it = theme_by_type.find("*");
4621 if (it != theme_by_type.end()) {
4622 for (const StyleSpec &spec : it->second)
4623 ret[(u32)spec.getState()] |= spec;
4626 it = theme_by_name.find("*");
4627 if (it != theme_by_name.end()) {
4628 for (const StyleSpec &spec : it->second)
4629 ret[(u32)spec.getState()] |= spec;
4632 if (!parent_type.empty()) {
4633 it = theme_by_type.find(parent_type);
4634 if (it != theme_by_type.end()) {
4635 for (const StyleSpec &spec : it->second)
4636 ret[(u32)spec.getState()] |= spec;
4640 it = theme_by_type.find(type);
4641 if (it != theme_by_type.end()) {
4642 for (const StyleSpec &spec : it->second)
4643 ret[(u32)spec.getState()] |= spec;
4646 it = theme_by_name.find(name);
4647 if (it != theme_by_name.end()) {
4648 for (const StyleSpec &spec : it->second)
4649 ret[(u32)spec.getState()] |= spec;