3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include "guiFormSpecMenu.h"
28 #include "constants.h"
30 #include "client/keycode.h"
31 #include "util/strfnd.h"
32 #include <IGUIButton.h>
33 #include <IGUICheckBox.h>
34 #include <IGUIComboBox.h>
35 #include <IGUIEditBox.h>
36 #include <IGUIStaticText.h>
38 #include <IGUITabControl.h>
39 #include "client/renderingengine.h"
41 #include "client/tile.h" // ITextureSource
42 #include "client/hud.h" // drawItemStack
46 #include "scripting_server.h"
47 #include "mainmenumanager.h"
50 #include "client/client.h"
51 #include "client/fontengine.h"
52 #include "client/sound.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "guiAnimatedImage.h"
59 #include "guiBackgroundImage.h"
61 #include "guiButton.h"
62 #include "guiButtonImage.h"
63 #include "guiButtonItemImage.h"
64 #include "guiEditBoxWithScrollbar.h"
65 #include "guiInventoryList.h"
66 #include "guiItemImage.h"
67 #include "guiScrollContainer.h"
68 #include "guiHyperText.h"
71 #define MY_CHECKPOS(a,b) \
72 if (v_pos.size() != 2) { \
73 errorstream<< "Invalid pos for element " << a << " specified: \"" \
74 << parts[b] << "\"" << std::endl; \
78 #define MY_CHECKGEOM(a,b) \
79 if (v_geom.size() != 2) { \
80 errorstream<< "Invalid geometry for element " << a << \
81 " specified: \"" << parts[b] << "\"" << std::endl; \
85 #define MY_CHECKCLIENT(a) \
87 errorstream << "Attempted to use element " << a << " with m_client == nullptr." << std::endl; \
94 static unsigned int font_line_height(gui::IGUIFont *font)
96 return font->getDimension(L"Ay").Height + font->getKerningHeight();
99 inline u32 clamp_u8(s32 value)
101 return (u32) MYMIN(MYMAX(value, 0), 255);
104 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
105 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
106 Client *client, gui::IGUIEnvironment *guienv, ISimpleTextureSource *tsrc,
107 ISoundManager *sound_manager, IFormSource *fsrc, TextDest *tdst,
108 const std::string &formspecPrepend, bool remap_dbl_click):
109 GUIModalMenu(guienv, parent, id, menumgr, remap_dbl_click),
112 m_sound_manager(sound_manager),
114 m_formspec_prepend(formspecPrepend),
119 current_keys_pending.key_down = false;
120 current_keys_pending.key_up = false;
121 current_keys_pending.key_enter = false;
122 current_keys_pending.key_escape = false;
124 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
125 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
128 GUIFormSpecMenu::~GUIFormSpecMenu()
132 for (auto &table_it : m_tables)
133 table_it.second->drop();
134 for (auto &inventorylist_it : m_inventorylists)
135 inventorylist_it->drop();
136 for (auto &checkbox_it : m_checkboxes)
137 checkbox_it.second->drop();
138 for (auto &scrollbar_it : m_scrollbars)
139 scrollbar_it.second->drop();
140 for (auto &background_it : m_backgrounds)
141 background_it->drop();
142 for (auto &tooltip_rect_it : m_tooltip_rects)
143 tooltip_rect_it.first->drop();
144 for (auto &clickthrough_it : m_clickthrough_elements)
145 clickthrough_it->drop();
146 for (auto &scroll_container_it : m_scroll_containers)
147 scroll_container_it.second->drop();
149 delete m_selected_item;
154 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
155 gui::IGUIEnvironment *guienv, JoystickController *joystick, IFormSource *fs_src,
156 TextDest *txt_dest, const std::string &formspecPrepend, ISoundManager *sound_manager)
158 if (cur_formspec == nullptr) {
159 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
160 client, guienv, client->getTextureSource(), sound_manager, fs_src,
161 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 bool GUIFormSpecMenu::precheckElement(const std::string &name, const std::string &element,
305 size_t args_min, size_t args_max, std::vector<std::string> &parts)
307 parts = split(element, ';');
308 if (parts.size() >= args_min && (parts.size() <= args_max || m_formspec_version > FORMSPEC_API_VERSION))
311 errorstream << "Invalid " << name << " element(" << parts.size() << "): '" << element << "'" << std::endl;
315 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
317 // Note: do not use precheckElement due to "," separator.
318 std::vector<std::string> parts = split(element,',');
320 if (((parts.size() == 2) || parts.size() == 3) ||
321 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
323 if (parts[1].find(';') != std::string::npos)
324 parts[1] = parts[1].substr(0,parts[1].find(';'));
326 data->invsize.X = MYMAX(0, stof(parts[0]));
327 data->invsize.Y = MYMAX(0, stof(parts[1]));
330 #ifndef HAVE_TOUCHSCREENGUI
331 if (parts.size() == 3) {
332 if (parts[2] == "true") {
333 lockSize(true,v2u32(800,600));
337 data->explicit_size = true;
340 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
343 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
345 std::vector<std::string> parts = split(element, ',');
347 if (parts.size() >= 2) {
348 if (parts[1].find(';') != std::string::npos)
349 parts[1] = parts[1].substr(0, parts[1].find(';'));
351 container_stack.push(pos_offset);
352 pos_offset.X += stof(parts[0]);
353 pos_offset.Y += stof(parts[1]);
356 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
359 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
361 if (container_stack.empty()) {
362 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
364 pos_offset = container_stack.top();
365 container_stack.pop();
369 void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
371 std::vector<std::string> parts;
372 if (!precheckElement("scroll_container start", element, 4, 5, parts))
375 std::vector<std::string> v_pos = split(parts[0], ',');
376 std::vector<std::string> v_geom = split(parts[1], ',');
377 std::string scrollbar_name = parts[2];
378 std::string orientation = parts[3];
379 f32 scroll_factor = 0.1f;
380 if (parts.size() >= 5 && !parts[4].empty())
381 scroll_factor = stof(parts[4]);
383 MY_CHECKPOS("scroll_container", 0);
384 MY_CHECKGEOM("scroll_container", 1);
386 v2s32 pos = getRealCoordinateBasePos(v_pos);
387 v2s32 geom = getRealCoordinateGeometry(v_geom);
389 if (orientation == "vertical")
390 scroll_factor *= -imgsize.Y;
391 else if (orientation == "horizontal")
392 scroll_factor *= -imgsize.X;
394 warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
395 << "Invalid scroll_container orientation: " << orientation
398 // old parent (at first: this)
399 // ^ is parent of clipper
400 // ^ is parent of mover
401 // ^ is parent of other elements
404 core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
406 gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
407 data->current_parent, 0, rect_clipper);
410 FieldSpec spec_mover(
414 258 + m_fields.size()
417 core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
419 GUIScrollContainer *mover = new GUIScrollContainer(Environment,
420 clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
422 data->current_parent = mover;
424 m_scroll_containers.emplace_back(scrollbar_name, mover);
426 m_fields.push_back(spec_mover);
430 // remove interferring offset of normal containers
431 container_stack.push(pos_offset);
436 void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
438 if (data->current_parent == this || data->current_parent->getParent() == this ||
439 container_stack.empty()) {
440 errorstream << "Invalid scroll_container end element, "
441 << "no matching scroll_container start element" << std::endl;
445 if (pos_offset.getLengthSQ() != 0.0f) {
446 // pos_offset is only set by containers and scroll_containers.
447 // scroll_containers always set it to 0,0 which means that if it is
448 // not 0,0, it is a normal container that was opened last, not a
450 errorstream << "Invalid scroll_container end element, "
451 << "an inner container was left open" << std::endl;
455 data->current_parent = data->current_parent->getParent()->getParent();
456 pos_offset = container_stack.top();
457 container_stack.pop();
460 void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
462 MY_CHECKCLIENT("list");
464 std::vector<std::string> parts;
465 if (!precheckElement("list", element, 4, 5, parts))
468 std::string location = parts[0];
469 std::string listname = parts[1];
470 std::vector<std::string> v_pos = split(parts[2],',');
471 std::vector<std::string> v_geom = split(parts[3],',');
472 std::string startindex;
473 if (parts.size() == 5)
474 startindex = parts[4];
476 MY_CHECKPOS("list",2);
477 MY_CHECKGEOM("list",3);
479 InventoryLocation loc;
481 if (location == "context" || location == "current_name")
482 loc = m_current_inventory_location;
484 loc.deSerialize(location);
487 geom.X = stoi(v_geom[0]);
488 geom.Y = stoi(v_geom[1]);
491 if (!startindex.empty())
492 start_i = stoi(startindex);
494 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
495 errorstream << "Invalid list element: '" << element << "'" << std::endl;
499 if (!data->explicit_size)
500 warningstream << "invalid use of list without a size[] element" << std::endl;
506 258 + m_fields.size(),
510 auto style = getDefaultStyleForElement("list", spec.fname);
512 v2f32 slot_scale = style.getVector2f(StyleSpec::SIZE, v2f32(0, 0));
514 slot_scale.X <= 0 ? imgsize.X : std::max<f32>(slot_scale.X * imgsize.X, 1),
515 slot_scale.Y <= 0 ? imgsize.Y : std::max<f32>(slot_scale.Y * imgsize.Y, 1)
518 v2f32 slot_spacing = style.getVector2f(StyleSpec::SPACING, v2f32(-1, -1));
519 v2f32 default_spacing = data->real_coordinates ?
520 v2f32(imgsize.X * 0.25f, imgsize.Y * 0.25f) :
521 v2f32(spacing.X - imgsize.X, spacing.Y - imgsize.Y);
523 slot_spacing.X = slot_spacing.X < 0 ? default_spacing.X :
524 imgsize.X * slot_spacing.X;
525 slot_spacing.Y = slot_spacing.Y < 0 ? default_spacing.Y :
526 imgsize.Y * slot_spacing.Y;
528 slot_spacing += slot_size;
530 v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) :
531 getElementBasePos(&v_pos);
533 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
534 pos.X + (geom.X - 1) * slot_spacing.X + slot_size.X,
535 pos.Y + (geom.Y - 1) * slot_spacing.Y + slot_size.Y);
537 GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
538 spec.fid, rect, m_invmgr, loc, listname, geom, start_i,
539 v2s32(slot_size.X, slot_size.Y), slot_spacing, this,
540 data->inventorylist_options, m_font);
542 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
544 m_inventorylists.push_back(e);
545 m_fields.push_back(spec);
548 void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
550 MY_CHECKCLIENT("listring");
552 std::vector<std::string> parts = split(element, ';');
554 if (parts.size() == 2) {
555 std::string location = parts[0];
556 std::string listname = parts[1];
558 InventoryLocation loc;
560 if (location == "context" || location == "current_name")
561 loc = m_current_inventory_location;
563 loc.deSerialize(location);
565 m_inventory_rings.emplace_back(loc, listname);
569 if (element.empty() && m_inventorylists.size() > 1) {
570 size_t siz = m_inventorylists.size();
571 // insert the last two inv list elements into the list ring
572 const GUIInventoryList *spa = m_inventorylists[siz - 2];
573 const GUIInventoryList *spb = m_inventorylists[siz - 1];
574 m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname());
575 m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname());
579 errorstream<< "Invalid list ring element(" << parts.size() << ", "
580 << m_inventorylists.size() << "): '" << element << "'" << std::endl;
583 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
585 std::vector<std::string> parts;
586 if (!precheckElement("checkbox", element, 3, 4, parts))
589 std::vector<std::string> v_pos = split(parts[0],',');
590 std::string name = parts[1];
591 std::string label = parts[2];
592 std::string selected;
594 if (parts.size() >= 4)
597 MY_CHECKPOS("checkbox",0);
599 bool fselected = false;
601 if (selected == "true")
604 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
605 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
606 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
607 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
610 core::rect<s32> rect;
612 if (data->real_coordinates) {
613 pos = getRealCoordinateBasePos(v_pos);
615 rect = core::rect<s32>(
618 pos.X + label_size.Width + cb_size + 7,
622 pos = getElementBasePos(&v_pos);
623 rect = core::rect<s32>(
625 pos.Y + imgsize.Y / 2 - y_center,
626 pos.X + label_size.Width + cb_size + 7,
627 pos.Y + imgsize.Y / 2 + y_center
633 wlabel, //Needed for displaying text on MSVC
638 spec.ftype = f_CheckBox;
640 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
641 data->current_parent, spec.fid, spec.flabel.c_str());
643 auto style = getDefaultStyleForElement("checkbox", name);
645 spec.sound = style.get(StyleSpec::Property::SOUND, "");
647 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
649 if (spec.fname == m_focused_element) {
650 Environment->setFocus(e);
654 m_checkboxes.emplace_back(spec, e);
655 m_fields.push_back(spec);
658 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
660 std::vector<std::string> parts;
661 if (!precheckElement("scrollbar", element, 5, 5, parts))
664 std::vector<std::string> v_pos = split(parts[0],',');
665 std::vector<std::string> v_geom = split(parts[1],',');
666 std::string name = parts[3];
667 std::string value = parts[4];
669 MY_CHECKPOS("scrollbar",0);
670 MY_CHECKGEOM("scrollbar",1);
675 if (data->real_coordinates) {
676 pos = getRealCoordinateBasePos(v_pos);
677 dim = getRealCoordinateGeometry(v_geom);
679 pos = getElementBasePos(&v_pos);
680 dim.X = stof(v_geom[0]) * spacing.X;
681 dim.Y = stof(v_geom[1]) * spacing.Y;
684 core::rect<s32> rect =
685 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
694 bool is_horizontal = true;
696 if (parts[2] == "vertical")
697 is_horizontal = false;
699 spec.ftype = f_ScrollBar;
701 GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent,
702 spec.fid, rect, is_horizontal, true);
704 auto style = getDefaultStyleForElement("scrollbar", name);
705 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
706 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
708 s32 max = data->scrollbar_options.max;
709 s32 min = data->scrollbar_options.min;
714 e->setPos(stoi(parts[4]));
716 e->setSmallStep(data->scrollbar_options.small_step);
717 e->setLargeStep(data->scrollbar_options.large_step);
719 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
721 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
723 if (spec.fname == m_focused_element) {
724 Environment->setFocus(e);
727 m_scrollbars.emplace_back(spec,e);
728 m_fields.push_back(spec);
731 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
733 std::vector<std::string> parts = split(element, ';');
735 if (parts.size() == 0) {
736 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
737 element << "'" << std::endl;
741 for (const std::string &i : parts) {
742 std::vector<std::string> options = split(i, '=');
744 if (options.size() != 2) {
745 warningstream << "Invalid scrollbaroptions option syntax: '" <<
746 element << "'" << std::endl;
747 continue; // Go to next option
750 if (options[0] == "max") {
751 data->scrollbar_options.max = stoi(options[1]);
753 } else if (options[0] == "min") {
754 data->scrollbar_options.min = stoi(options[1]);
756 } else if (options[0] == "smallstep") {
757 int value = stoi(options[1]);
758 data->scrollbar_options.small_step = value < 0 ? 10 : value;
760 } else if (options[0] == "largestep") {
761 int value = stoi(options[1]);
762 data->scrollbar_options.large_step = value < 0 ? 100 : value;
764 } else if (options[0] == "thumbsize") {
765 int value = stoi(options[1]);
766 data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
768 } else if (options[0] == "arrows") {
769 std::string value = trim(options[1]);
771 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
772 else if (value == "show")
773 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
774 else // Auto hide/show
775 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
779 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
780 "): '" << element << "'" << std::endl;
784 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
786 std::vector<std::string> parts;
787 if (!precheckElement("image", element, 2, 3, parts))
790 if (parts.size() >= 3) {
791 std::vector<std::string> v_pos = split(parts[0],',');
792 std::vector<std::string> v_geom = split(parts[1],',');
793 std::string name = unescape_string(parts[2]);
795 MY_CHECKPOS("image", 0);
796 MY_CHECKGEOM("image", 1);
801 if (data->real_coordinates) {
802 pos = getRealCoordinateBasePos(v_pos);
803 geom = getRealCoordinateGeometry(v_geom);
805 pos = getElementBasePos(&v_pos);
806 geom.X = stof(v_geom[0]) * (float)imgsize.X;
807 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
810 if (!data->explicit_size)
811 warningstream<<"invalid use of image without a size[] element"<<std::endl;
813 video::ITexture *texture = m_tsrc->getTexture(name);
815 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
816 << std::endl << "\t" << name << std::endl;
824 258 + m_fields.size(),
827 core::rect<s32> rect(pos, pos + geom);
828 gui::IGUIImage *e = Environment->addImage(rect, data->current_parent,
830 e->setImage(texture);
831 e->setScaleImage(true);
832 auto style = getDefaultStyleForElement("image", spec.fname);
833 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
834 m_fields.push_back(spec);
836 // images should let events through
838 m_clickthrough_elements.push_back(e);
842 // Else: 2 arguments in "parts"
844 std::vector<std::string> v_pos = split(parts[0],',');
845 std::string name = unescape_string(parts[1]);
847 MY_CHECKPOS("image", 0);
849 v2s32 pos = getElementBasePos(&v_pos);
851 if (!data->explicit_size)
852 warningstream<<"invalid use of image without a size[] element"<<std::endl;
854 video::ITexture *texture = m_tsrc->getTexture(name);
856 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
857 << std::endl << "\t" << name << std::endl;
865 258 + m_fields.size()
867 gui::IGUIImage *e = Environment->addImage(texture, pos, true,
868 data->current_parent, spec.fid, 0);
869 auto style = getDefaultStyleForElement("image", spec.fname);
870 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
871 m_fields.push_back(spec);
873 // images should let events through
875 m_clickthrough_elements.push_back(e);
878 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
880 std::vector<std::string> parts;
881 if (!precheckElement("animated_image", element, 6, 7, parts))
884 std::vector<std::string> v_pos = split(parts[0], ',');
885 std::vector<std::string> v_geom = split(parts[1], ',');
886 std::string name = parts[2];
887 std::string texture_name = unescape_string(parts[3]);
888 s32 frame_count = stoi(parts[4]);
889 s32 frame_duration = stoi(parts[5]);
891 MY_CHECKPOS("animated_image", 0);
892 MY_CHECKGEOM("animated_image", 1);
897 if (data->real_coordinates) {
898 pos = getRealCoordinateBasePos(v_pos);
899 geom = getRealCoordinateGeometry(v_geom);
901 pos = getElementBasePos(&v_pos);
902 geom.X = stof(v_geom[0]) * (float)imgsize.X;
903 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
906 if (!data->explicit_size)
907 warningstream << "Invalid use of animated_image without a size[] element" << std::endl;
913 258 + m_fields.size()
915 spec.ftype = f_AnimatedImage;
918 core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
920 GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent, spec.fid,
921 rect, texture_name, frame_count, frame_duration, m_tsrc);
923 if (parts.size() >= 7)
924 e->setFrameIndex(stoi(parts[6]) - 1);
926 auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
927 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
929 // Animated images should let events through
930 m_clickthrough_elements.push_back(e);
932 m_fields.push_back(spec);
935 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
937 std::vector<std::string> parts;
938 if (!precheckElement("item_image", element, 3, 3, parts))
941 std::vector<std::string> v_pos = split(parts[0],',');
942 std::vector<std::string> v_geom = split(parts[1],',');
943 std::string name = parts[2];
945 MY_CHECKPOS("item_image",0);
946 MY_CHECKGEOM("item_image",1);
951 if (data->real_coordinates) {
952 pos = getRealCoordinateBasePos(v_pos);
953 geom = getRealCoordinateGeometry(v_geom);
955 pos = getElementBasePos(&v_pos);
956 geom.X = stof(v_geom[0]) * (float)imgsize.X;
957 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
960 if(!data->explicit_size)
961 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
967 258 + m_fields.size(),
970 spec.ftype = f_ItemImage;
972 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
973 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
974 auto style = getDefaultStyleForElement("item_image", spec.fname);
975 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
977 // item images should let events through
978 m_clickthrough_elements.push_back(e);
980 m_fields.push_back(spec);
983 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
984 const std::string &type)
986 std::vector<std::string> parts;
987 if (!precheckElement("button", element, 4, 4, parts))
990 std::vector<std::string> v_pos = split(parts[0],',');
991 std::vector<std::string> v_geom = split(parts[1],',');
992 std::string name = parts[2];
993 std::string label = parts[3];
995 MY_CHECKPOS("button",0);
996 MY_CHECKGEOM("button",1);
1000 core::rect<s32> rect;
1002 if (data->real_coordinates) {
1003 pos = getRealCoordinateBasePos(v_pos);
1004 geom = getRealCoordinateGeometry(v_geom);
1005 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1008 pos = getElementBasePos(&v_pos);
1009 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1010 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1012 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
1013 pos.X + geom.X, pos.Y + m_btn_height);
1016 if(!data->explicit_size)
1017 warningstream<<"invalid use of button without a size[] element"<<std::endl;
1019 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1025 258 + m_fields.size()
1027 spec.ftype = f_Button;
1028 if(type == "button_exit")
1029 spec.is_exit = true;
1031 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1032 data->current_parent, spec.fid, spec.flabel.c_str());
1034 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1036 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1038 e->setStyles(style);
1040 if (spec.fname == m_focused_element) {
1041 Environment->setFocus(e);
1044 m_fields.push_back(spec);
1047 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1049 std::vector<std::string> parts;
1050 if (!precheckElement("background", element, 3, 5, parts))
1053 std::vector<std::string> v_pos = split(parts[0],',');
1054 std::vector<std::string> v_geom = split(parts[1],',');
1055 std::string name = unescape_string(parts[2]);
1057 MY_CHECKPOS("background",0);
1058 MY_CHECKGEOM("background",1);
1063 if (data->real_coordinates) {
1064 pos = getRealCoordinateBasePos(v_pos);
1065 geom = getRealCoordinateGeometry(v_geom);
1067 pos = getElementBasePos(&v_pos);
1068 pos.X -= (spacing.X - (float)imgsize.X) / 2;
1069 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1071 geom.X = stof(v_geom[0]) * spacing.X;
1072 geom.Y = stof(v_geom[1]) * spacing.Y;
1076 if (parts.size() >= 4 && is_yes(parts[3])) {
1077 if (data->real_coordinates) {
1078 pos = getRealCoordinateBasePos(v_pos) * -1;
1081 pos.X = stoi(v_pos[0]); //acts as offset
1082 pos.Y = stoi(v_pos[1]);
1087 core::rect<s32> middle;
1088 if (parts.size() >= 5) {
1089 std::vector<std::string> v_middle = split(parts[4], ',');
1090 if (v_middle.size() == 1) {
1091 s32 x = stoi(v_middle[0]);
1092 middle.UpperLeftCorner = core::vector2di(x, x);
1093 middle.LowerRightCorner = core::vector2di(-x, -x);
1094 } else if (v_middle.size() == 2) {
1095 s32 x = stoi(v_middle[0]);
1096 s32 y = stoi(v_middle[1]);
1097 middle.UpperLeftCorner = core::vector2di(x, y);
1098 middle.LowerRightCorner = core::vector2di(-x, -y);
1099 // `-x` is interpreted as `w - x`
1100 } else if (v_middle.size() == 4) {
1101 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1102 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1104 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1108 if (!data->explicit_size && !clip)
1109 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1115 258 + m_fields.size()
1118 core::rect<s32> rect;
1120 // no auto_clip => position like normal image
1121 rect = core::rect<s32>(pos, pos + geom);
1123 // it will be auto-clipped when drawing
1124 rect = core::rect<s32>(-pos, pos);
1127 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1128 rect, name, middle, m_tsrc, clip);
1130 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1132 e->setNotClipped(true);
1134 e->setVisible(false); // the element is drawn manually before all others
1136 m_backgrounds.push_back(e);
1137 m_fields.push_back(spec);
1140 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1142 std::vector<std::string> parts = split(element,';');
1144 data->table_options.clear();
1145 for (const std::string &part : parts) {
1146 // Parse table option
1147 std::string opt = unescape_string(part);
1148 data->table_options.push_back(GUITable::splitOption(opt));
1152 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1154 std::vector<std::string> parts = split(element,';');
1156 data->table_columns.clear();
1157 for (const std::string &part : parts) {
1158 std::vector<std::string> col_parts = split(part,',');
1159 GUITable::TableColumn column;
1160 // Parse column type
1161 if (!col_parts.empty())
1162 column.type = col_parts[0];
1163 // Parse column options
1164 for (size_t j = 1; j < col_parts.size(); ++j) {
1165 std::string opt = unescape_string(col_parts[j]);
1166 column.options.push_back(GUITable::splitOption(opt));
1168 data->table_columns.push_back(column);
1172 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1174 std::vector<std::string> parts;
1175 if (!precheckElement("table", element, 4, 5, parts))
1178 std::vector<std::string> v_pos = split(parts[0],',');
1179 std::vector<std::string> v_geom = split(parts[1],',');
1180 std::string name = parts[2];
1181 std::vector<std::string> items = split(parts[3],',');
1182 std::string str_initial_selection;
1183 std::string str_transparent = "false";
1185 if (parts.size() >= 5)
1186 str_initial_selection = parts[4];
1188 MY_CHECKPOS("table",0);
1189 MY_CHECKGEOM("table",1);
1194 if (data->real_coordinates) {
1195 pos = getRealCoordinateBasePos(v_pos);
1196 geom = getRealCoordinateGeometry(v_geom);
1198 pos = getElementBasePos(&v_pos);
1199 geom.X = stof(v_geom[0]) * spacing.X;
1200 geom.Y = stof(v_geom[1]) * spacing.Y;
1203 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1209 258 + m_fields.size()
1212 spec.ftype = f_Table;
1214 for (std::string &item : items) {
1215 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1218 //now really show table
1219 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1222 if (spec.fname == m_focused_element) {
1223 Environment->setFocus(e);
1226 e->setTable(data->table_options, data->table_columns, items);
1228 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1229 e->setDynamicData(data->table_dyndata[name]);
1232 if (!str_initial_selection.empty() && str_initial_selection != "0")
1233 e->setSelected(stoi(str_initial_selection));
1235 auto style = getDefaultStyleForElement("table", name);
1236 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1237 e->setOverrideFont(style.getFont());
1239 m_tables.emplace_back(spec, e);
1240 m_fields.push_back(spec);
1243 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1245 std::vector<std::string> parts;
1246 if (!precheckElement("textlist", element, 4, 6, parts))
1249 std::vector<std::string> v_pos = split(parts[0],',');
1250 std::vector<std::string> v_geom = split(parts[1],',');
1251 std::string name = parts[2];
1252 std::vector<std::string> items = split(parts[3],',');
1253 std::string str_initial_selection;
1254 std::string str_transparent = "false";
1256 if (parts.size() >= 5)
1257 str_initial_selection = parts[4];
1259 if (parts.size() >= 6)
1260 str_transparent = parts[5];
1262 MY_CHECKPOS("textlist",0);
1263 MY_CHECKGEOM("textlist",1);
1268 if (data->real_coordinates) {
1269 pos = getRealCoordinateBasePos(v_pos);
1270 geom = getRealCoordinateGeometry(v_geom);
1272 pos = getElementBasePos(&v_pos);
1273 geom.X = stof(v_geom[0]) * spacing.X;
1274 geom.Y = stof(v_geom[1]) * spacing.Y;
1277 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1283 258 + m_fields.size()
1286 spec.ftype = f_Table;
1288 for (std::string &item : items) {
1289 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1292 //now really show list
1293 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1296 if (spec.fname == m_focused_element) {
1297 Environment->setFocus(e);
1300 e->setTextList(items, is_yes(str_transparent));
1302 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1303 e->setDynamicData(data->table_dyndata[name]);
1306 if (!str_initial_selection.empty() && str_initial_selection != "0")
1307 e->setSelected(stoi(str_initial_selection));
1309 auto style = getDefaultStyleForElement("textlist", name);
1310 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1311 e->setOverrideFont(style.getFont());
1313 m_tables.emplace_back(spec, e);
1314 m_fields.push_back(spec);
1317 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1319 std::vector<std::string> parts;
1320 if (!precheckElement("dropdown", element, 5, 6, parts))
1323 std::vector<std::string> v_pos = split(parts[0], ',');
1324 std::string name = parts[2];
1325 std::vector<std::string> items = split(parts[3], ',');
1326 std::string str_initial_selection = parts[4];
1328 if (parts.size() >= 6 && is_yes(parts[5]))
1329 m_dropdown_index_event[name] = true;
1331 MY_CHECKPOS("dropdown",0);
1335 core::rect<s32> rect;
1337 if (data->real_coordinates) {
1338 std::vector<std::string> v_geom = split(parts[1],',');
1340 if (v_geom.size() == 1)
1341 v_geom.emplace_back("1");
1343 MY_CHECKGEOM("dropdown",1);
1345 pos = getRealCoordinateBasePos(v_pos);
1346 geom = getRealCoordinateGeometry(v_geom);
1347 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1349 pos = getElementBasePos(&v_pos);
1351 s32 width = stof(parts[1]) * spacing.Y;
1353 rect = core::rect<s32>(pos.X, pos.Y,
1354 pos.X + width, pos.Y + (m_btn_height * 2));
1361 258 + m_fields.size()
1364 spec.ftype = f_DropDown;
1367 //now really show list
1368 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1371 if (spec.fname == m_focused_element) {
1372 Environment->setFocus(e);
1375 for (const std::string &item : items) {
1376 e->addItem(unescape_translate(unescape_string(
1377 utf8_to_wide(item))).c_str());
1380 if (!str_initial_selection.empty())
1381 e->setSelected(stoi(str_initial_selection)-1);
1383 auto style = getDefaultStyleForElement("dropdown", name);
1385 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1387 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1389 m_fields.push_back(spec);
1391 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1392 std::vector<std::string> &values = m_dropdowns.back().second;
1393 for (const std::string &item : items) {
1394 values.push_back(unescape_string(item));
1398 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1400 std::vector<std::string> parts;
1401 if (!precheckElement("field_close_on_enter", element, 2, 2, parts))
1404 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1407 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1409 std::vector<std::string> parts;
1410 if (!precheckElement("pwdfield", element, 4, 4, parts))
1413 std::vector<std::string> v_pos = split(parts[0],',');
1414 std::vector<std::string> v_geom = split(parts[1],',');
1415 std::string name = parts[2];
1416 std::string label = parts[3];
1418 MY_CHECKPOS("pwdfield",0);
1419 MY_CHECKGEOM("pwdfield",1);
1424 if (data->real_coordinates) {
1425 pos = getRealCoordinateBasePos(v_pos);
1426 geom = getRealCoordinateGeometry(v_geom);
1428 pos = getElementBasePos(&v_pos);
1431 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1433 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1434 pos.Y -= m_btn_height;
1435 geom.Y = m_btn_height*2;
1438 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1440 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1446 258 + m_fields.size(),
1452 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1453 data->current_parent, spec.fid);
1455 if (spec.fname == m_focused_element) {
1456 Environment->setFocus(e);
1459 if (label.length() >= 1) {
1460 int font_height = g_fontengine->getTextHeight();
1461 rect.UpperLeftCorner.Y -= font_height;
1462 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1463 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1464 data->current_parent, 0);
1467 e->setPasswordBox(true,L'*');
1469 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1470 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1471 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1472 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1473 e->setOverrideFont(style.getFont());
1476 evt.EventType = EET_KEY_INPUT_EVENT;
1477 evt.KeyInput.Key = KEY_END;
1478 evt.KeyInput.Char = 0;
1479 evt.KeyInput.Control = false;
1480 evt.KeyInput.Shift = false;
1481 evt.KeyInput.PressedDown = true;
1484 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1485 // warning referring to field_close_on_enter[]!
1487 m_fields.push_back(spec);
1490 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1491 core::rect<s32> &rect, bool is_multiline)
1493 bool is_editable = !spec.fname.empty();
1494 if (!is_editable && !is_multiline) {
1495 // spec field id to 0, this stops submit searching for a value that isn't there
1496 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1497 data->current_parent, 0);
1503 } else if (is_multiline &&
1504 spec.fdefault.empty() && !spec.flabel.empty()) {
1505 // Multiline textareas: swap default and label for backwards compat
1506 spec.flabel.swap(spec.fdefault);
1509 gui::IGUIEditBox *e = nullptr;
1511 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1512 data->current_parent, spec.fid, rect, is_editable, true);
1513 } else if (is_editable) {
1514 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1515 data->current_parent, spec.fid);
1519 auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1522 if (is_editable && spec.fname == m_focused_element)
1523 Environment->setFocus(e);
1526 e->setMultiLine(true);
1527 e->setWordWrap(true);
1528 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1531 evt.EventType = EET_KEY_INPUT_EVENT;
1532 evt.KeyInput.Key = KEY_END;
1533 evt.KeyInput.Char = 0;
1534 evt.KeyInput.Control = 0;
1535 evt.KeyInput.Shift = 0;
1536 evt.KeyInput.PressedDown = true;
1540 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1541 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1542 bool border = style.getBool(StyleSpec::BORDER, true);
1543 e->setDrawBorder(border);
1544 e->setDrawBackground(border);
1545 e->setOverrideFont(style.getFont());
1550 if (!spec.flabel.empty()) {
1551 int font_height = g_fontengine->getTextHeight();
1552 rect.UpperLeftCorner.Y -= font_height;
1553 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1554 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1555 rect, false, true, data->current_parent, 0);
1558 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1562 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1563 std::vector<std::string> &parts)
1565 std::string name = parts[0];
1566 std::string label = parts[1];
1567 std::string default_val = parts[2];
1569 core::rect<s32> rect;
1571 if (data->explicit_size)
1572 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1574 v2s32 pos = getElementBasePos(nullptr);
1575 pos.Y = (data->simple_field_count + 2) * 60;
1576 v2s32 size = DesiredRect.getSize();
1578 rect = core::rect<s32>(
1579 size.X / 2 - 150, pos.Y,
1580 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1585 default_val = m_form_src->resolveText(default_val);
1588 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1593 utf8_to_wide(unescape_string(default_val)),
1594 258 + m_fields.size(),
1599 createTextField(data, spec, rect, false);
1601 m_fields.push_back(spec);
1603 data->simple_field_count++;
1606 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1607 const std::string &type)
1609 std::vector<std::string> v_pos = split(parts[0],',');
1610 std::vector<std::string> v_geom = split(parts[1],',');
1611 std::string name = parts[2];
1612 std::string label = parts[3];
1613 std::string default_val = parts[4];
1615 MY_CHECKPOS(type,0);
1616 MY_CHECKGEOM(type,1);
1621 if (data->real_coordinates) {
1622 pos = getRealCoordinateBasePos(v_pos);
1623 geom = getRealCoordinateGeometry(v_geom);
1625 pos = getElementBasePos(&v_pos);
1628 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1630 if (type == "textarea")
1632 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1633 pos.Y += m_btn_height;
1637 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1638 pos.Y -= m_btn_height;
1639 geom.Y = m_btn_height*2;
1643 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1645 if(!data->explicit_size)
1646 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1649 default_val = m_form_src->resolveText(default_val);
1652 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1657 utf8_to_wide(unescape_string(default_val)),
1658 258 + m_fields.size(),
1663 createTextField(data, spec, rect, type == "textarea");
1665 // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1666 // warning referring to field_close_on_enter[]!
1668 m_fields.push_back(spec);
1671 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1672 const std::string &type)
1674 std::vector<std::string> parts;
1675 if (!precheckElement(type, element, 3, 5, parts))
1678 if (parts.size() == 3 || parts.size() == 4) {
1679 parseSimpleField(data, parts);
1683 // Else: >= 5 arguments in "parts"
1684 parseTextArea(data, parts, type);
1687 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1689 MY_CHECKCLIENT("list");
1691 std::vector<std::string> parts;
1692 if (!precheckElement("hypertext", element, 4, 4, parts))
1695 std::vector<std::string> v_pos = split(parts[0], ',');
1696 std::vector<std::string> v_geom = split(parts[1], ',');
1697 std::string name = parts[2];
1698 std::string text = parts[3];
1700 MY_CHECKPOS("hypertext", 0);
1701 MY_CHECKGEOM("hypertext", 1);
1706 if (data->real_coordinates) {
1707 pos = getRealCoordinateBasePos(v_pos);
1708 geom = getRealCoordinateGeometry(v_geom);
1710 pos = getElementBasePos(&v_pos);
1713 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1714 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1715 pos.Y += m_btn_height;
1718 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1721 text = m_form_src->resolveText(text);
1725 translate_string(utf8_to_wide(unescape_string(text))),
1727 258 + m_fields.size()
1730 spec.ftype = f_HyperText;
1732 auto style = getDefaultStyleForElement("hypertext", spec.fname);
1733 spec.sound = style.get(StyleSpec::Property::SOUND, "");
1735 GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1736 data->current_parent, spec.fid, rect, m_client, m_tsrc);
1739 m_fields.push_back(spec);
1742 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1744 std::vector<std::string> parts;
1745 if (!precheckElement("label", element, 2, 2, parts))
1748 std::vector<std::string> v_pos = split(parts[0],',');
1749 std::string text = parts[1];
1751 MY_CHECKPOS("label",0);
1753 if(!data->explicit_size)
1754 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1756 std::vector<std::string> lines = split(text, '\n');
1758 auto style = getDefaultStyleForElement("label", "");
1759 gui::IGUIFont *font = style.getFont();
1763 for (unsigned int i = 0; i != lines.size(); i++) {
1764 std::wstring wlabel_colors = translate_string(
1765 utf8_to_wide(unescape_string(lines[i])));
1766 // Without color escapes to get the font dimensions
1767 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1769 core::rect<s32> rect;
1771 if (data->real_coordinates) {
1772 // Lines are spaced at the distance of 1/2 imgsize.
1773 // This alows lines that line up with the new elements
1774 // easily without sacrificing good line distance. If
1775 // it was one whole imgsize, it would have too much
1777 v2s32 pos = getRealCoordinateBasePos(v_pos);
1779 // Labels are positioned by their center, not their top.
1780 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1782 rect = core::rect<s32>(
1784 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1788 // Lines are spaced at the nominal distance of
1789 // 2/5 inventory slot, even if the font doesn't
1790 // quite match that. This provides consistent
1791 // form layout, at the expense of sometimes
1792 // having sub-optimal spacing for the font.
1793 // We multiply by 2 and then divide by 5, rather
1794 // than multiply by 0.4, to get exact results
1795 // in the integer cases: 0.4 is not exactly
1796 // representable in binary floating point.
1798 v2s32 pos = getElementBasePos(nullptr);
1799 pos.X += stof(v_pos[0]) * spacing.X;
1800 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1802 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1804 rect = core::rect<s32>(
1805 pos.X, pos.Y - m_btn_height,
1806 pos.X + font->getDimension(wlabel_plain.c_str()).Width,
1807 pos.Y + m_btn_height);
1814 258 + m_fields.size(),
1817 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1818 spec.flabel.c_str(), rect, false, false, data->current_parent,
1820 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1822 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1823 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1824 e->setOverrideFont(font);
1826 m_fields.push_back(spec);
1828 // labels should let events through
1830 m_clickthrough_elements.push_back(e);
1834 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1836 std::vector<std::string> parts;
1837 if (!precheckElement("vertlabel", element, 2, 2, parts))
1840 std::vector<std::string> v_pos = split(parts[0],',');
1841 std::wstring text = unescape_translate(
1842 unescape_string(utf8_to_wide(parts[1])));
1844 MY_CHECKPOS("vertlabel",1);
1846 auto style = getDefaultStyleForElement("vertlabel", "", "label");
1847 gui::IGUIFont *font = style.getFont();
1852 core::rect<s32> rect;
1854 if (data->real_coordinates) {
1855 pos = getRealCoordinateBasePos(v_pos);
1857 // Vertlabels are positioned by center, not left.
1858 pos.X -= imgsize.X / 2;
1860 // We use text.length + 1 because without it, the rect
1861 // isn't quite tall enough and cuts off the text.
1862 rect = core::rect<s32>(pos.X, pos.Y,
1864 pos.Y + font_line_height(font) *
1865 (text.length() + 1));
1868 pos = getElementBasePos(&v_pos);
1870 // As above, the length must be one longer. The width of
1871 // the rect (15 pixels) seems rather arbitrary, but
1872 // changing it might break something.
1873 rect = core::rect<s32>(
1874 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1876 font_line_height(font) *
1877 (text.length() + 1) +
1878 ((imgsize.Y/2) - m_btn_height));
1881 if(!data->explicit_size)
1882 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1886 for (wchar_t i : text) {
1895 258 + m_fields.size()
1897 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1898 rect, false, false, data->current_parent, spec.fid);
1899 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1901 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1902 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1903 e->setOverrideFont(font);
1905 m_fields.push_back(spec);
1907 // vertlabels should let events through
1909 m_clickthrough_elements.push_back(e);
1912 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1913 const std::string &type)
1915 std::vector<std::string> parts;
1916 if (!precheckElement("image_button", element, 5, 8, parts))
1919 if (parts.size() == 6) {
1920 // Invalid argument count.
1921 errorstream << "Invalid image_button element(" << parts.size() << "): '" << element << "'" << std::endl;
1925 std::vector<std::string> v_pos = split(parts[0],',');
1926 std::vector<std::string> v_geom = split(parts[1],',');
1927 std::string image_name = parts[2];
1928 std::string name = parts[3];
1929 std::string label = parts[4];
1931 MY_CHECKPOS("image_button",0);
1932 MY_CHECKGEOM("image_button",1);
1934 std::string pressed_image_name;
1936 if (parts.size() >= 8) {
1937 pressed_image_name = parts[7];
1943 if (data->real_coordinates) {
1944 pos = getRealCoordinateBasePos(v_pos);
1945 geom = getRealCoordinateGeometry(v_geom);
1947 pos = getElementBasePos(&v_pos);
1948 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1949 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1952 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1955 if (!data->explicit_size)
1956 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1958 image_name = unescape_string(image_name);
1959 pressed_image_name = unescape_string(pressed_image_name);
1961 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1966 utf8_to_wide(image_name),
1967 258 + m_fields.size()
1969 spec.ftype = f_Button;
1970 if (type == "image_button_exit")
1971 spec.is_exit = true;
1973 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1974 data->current_parent, spec.fid, spec.flabel.c_str());
1976 if (spec.fname == m_focused_element) {
1977 Environment->setFocus(e);
1980 auto style = getStyleForElement("image_button", spec.fname);
1982 spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
1984 // Override style properties with values specified directly in the element
1985 if (!image_name.empty())
1986 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1988 if (!pressed_image_name.empty())
1989 style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
1991 if (parts.size() >= 7) {
1992 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
1993 style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
1996 e->setStyles(style);
1997 e->setScaleImage(true);
1999 m_fields.push_back(spec);
2002 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2004 std::vector<std::string> parts;
2005 if (!precheckElement("tabheader", element, 4, 7, parts))
2008 // Length 7: Additional "height" parameter after "pos". Only valid with real_coordinates.
2009 // Note: New arguments for the "height" syntax cannot be added without breaking older clients.
2010 if (parts.size() == 5 || (parts.size() == 7 && !data->real_coordinates)) {
2011 errorstream << "Invalid tabheader element(" << parts.size() << "): '"
2012 << element << "'" << std::endl;
2016 std::vector<std::string> v_pos = split(parts[0],',');
2018 // If we're using real coordinates, add an extra field for height.
2019 // Width is not here because tabs are the width of the text, and
2020 // there's no reason to change that.
2022 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2023 bool auto_width = true;
2024 if (parts.size() == 7) {
2027 v_geom = split(parts[1], ',');
2028 if (v_geom.size() == 1)
2029 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2034 std::string name = parts[i+1];
2035 std::vector<std::string> buttons = split(parts[i+2], ',');
2036 std::string str_index = parts[i+3];
2037 bool show_background = true;
2038 bool show_border = true;
2039 int tab_index = stoi(str_index) - 1;
2041 MY_CHECKPOS("tabheader", 0);
2043 if (parts.size() == 6 + i) {
2044 if (parts[4+i] == "true")
2045 show_background = false;
2046 if (parts[5+i] == "false")
2047 show_border = false;
2054 258 + m_fields.size()
2057 spec.ftype = f_TabHeader;
2062 if (data->real_coordinates) {
2063 pos = getRealCoordinateBasePos(v_pos);
2065 geom = getRealCoordinateGeometry(v_geom);
2066 // Set default height
2067 if (parts.size() <= 6)
2068 geom.Y = m_btn_height * 2;
2069 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2071 geom.X = DesiredRect.getWidth(); // Set automatic width
2073 MY_CHECKGEOM("tabheader", 1);
2075 v2f32 pos_f = pos_offset * spacing;
2076 pos_f.X += stof(v_pos[0]) * spacing.X;
2077 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2078 pos = v2s32(pos_f.X, pos_f.Y);
2080 geom.Y = m_btn_height * 2;
2081 geom.X = DesiredRect.getWidth();
2084 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2087 gui::IGUITabControl *e = Environment->addTabControl(rect,
2088 data->current_parent, show_background, show_border, spec.fid);
2089 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2090 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2091 e->setTabHeight(geom.Y);
2093 auto style = getDefaultStyleForElement("tabheader", name);
2095 spec.sound = style.get(StyleSpec::Property::SOUND, "");
2097 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2099 for (const std::string &button : buttons) {
2100 auto tab = e->addTab(unescape_translate(unescape_string(
2101 utf8_to_wide(button))).c_str(), -1);
2102 if (style.isNotDefault(StyleSpec::BGCOLOR))
2103 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2105 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2108 if ((tab_index >= 0) &&
2109 (buttons.size() < INT_MAX) &&
2110 (tab_index < (int) buttons.size()))
2111 e->setActiveTab(tab_index);
2113 m_fields.push_back(spec);
2116 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2118 MY_CHECKCLIENT("item_image_button");
2120 std::vector<std::string> parts;
2121 if (!precheckElement("item_image_button", element, 5, 5, parts))
2124 std::vector<std::string> v_pos = split(parts[0],',');
2125 std::vector<std::string> v_geom = split(parts[1],',');
2126 std::string item_name = parts[2];
2127 std::string name = parts[3];
2128 std::string label = parts[4];
2130 label = unescape_string(label);
2131 item_name = unescape_string(item_name);
2133 MY_CHECKPOS("item_image_button",0);
2134 MY_CHECKGEOM("item_image_button",1);
2139 if (data->real_coordinates) {
2140 pos = getRealCoordinateBasePos(v_pos);
2141 geom = getRealCoordinateGeometry(v_geom);
2143 pos = getElementBasePos(&v_pos);
2144 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2145 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2148 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2150 if(!data->explicit_size)
2151 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2153 IItemDefManager *idef = m_client->idef();
2155 item.deSerialize(item_name, idef);
2158 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2159 m_default_tooltip_bgcolor,
2160 m_default_tooltip_color);
2162 // the spec for the button
2165 utf8_to_wide(label),
2166 utf8_to_wide(item_name),
2167 258 + m_fields.size(),
2171 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2172 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2173 item_name, m_client);
2175 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2177 spec_btn.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
2179 e_btn->setStyles(style);
2181 if (spec_btn.fname == m_focused_element) {
2182 Environment->setFocus(e_btn);
2185 spec_btn.ftype = f_Button;
2186 rect += data->basepos-padding;
2187 spec_btn.rect = rect;
2188 m_fields.push_back(spec_btn);
2191 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2193 std::vector<std::string> parts;
2194 if (!precheckElement("box", element, 3, 3, parts))
2197 std::vector<std::string> v_pos = split(parts[0], ',');
2198 std::vector<std::string> v_geom = split(parts[1], ',');
2200 MY_CHECKPOS("box", 0);
2201 MY_CHECKGEOM("box", 1);
2206 if (data->real_coordinates) {
2207 pos = getRealCoordinateBasePos(v_pos);
2208 geom = getRealCoordinateGeometry(v_geom);
2210 pos = getElementBasePos(&v_pos);
2211 geom.X = stof(v_geom[0]) * spacing.X;
2212 geom.Y = stof(v_geom[1]) * spacing.Y;
2219 258 + m_fields.size(),
2224 auto style = getDefaultStyleForElement("box", spec.fname);
2226 video::SColor tmp_color;
2227 std::array<video::SColor, 4> colors;
2228 std::array<video::SColor, 4> bordercolors = {0x0, 0x0, 0x0, 0x0};
2229 std::array<s32, 4> borderwidths = {0, 0, 0, 0};
2231 if (parseColorString(parts[2], tmp_color, true, 0x8C)) {
2232 colors = {tmp_color, tmp_color, tmp_color, tmp_color};
2234 colors = style.getColorArray(StyleSpec::COLORS, {0x0, 0x0, 0x0, 0x0});
2235 bordercolors = style.getColorArray(StyleSpec::BORDERCOLORS,
2236 {0x0, 0x0, 0x0, 0x0});
2237 borderwidths = style.getIntArray(StyleSpec::BORDERWIDTHS, {0, 0, 0, 0});
2240 core::rect<s32> rect(pos, pos + geom);
2242 GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid, rect,
2243 colors, bordercolors, borderwidths);
2244 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2247 m_fields.push_back(spec);
2250 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2252 std::vector<std::string> parts;
2253 if (!precheckElement("bgcolor", element, 1, 3, parts))
2256 const u32 parameter_count = parts.size();
2258 if (parameter_count > 2 && m_formspec_version < 3) {
2259 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2260 << element << "'" << std::endl;
2265 if (parameter_count >= 1 && parts[0] != "")
2266 parseColorString(parts[0], m_bgcolor, false);
2269 if (parameter_count >= 2) {
2270 if (parts[1] == "both") {
2271 m_bgnonfullscreen = true;
2272 m_bgfullscreen = true;
2273 } else if (parts[1] == "neither") {
2274 m_bgnonfullscreen = false;
2275 m_bgfullscreen = false;
2276 } else if (parts[1] != "" || m_formspec_version < 3) {
2277 m_bgfullscreen = is_yes(parts[1]);
2278 m_bgnonfullscreen = !m_bgfullscreen;
2283 if (parameter_count >= 3 && parts[2] != "")
2284 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2287 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2289 std::vector<std::string> parts;
2290 // Legacy Note: If clients older than 5.5.0-dev are supplied with additional arguments,
2291 // the tooltip colors will be ignored.
2292 if (!precheckElement("listcolors", element, 2, 5, parts))
2295 if (parts.size() == 4) {
2296 // Invalid argument combination
2297 errorstream << "Invalid listcolors element(" << parts.size() << "): '"
2298 << element << "'" << std::endl;
2302 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2303 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2305 if (parts.size() >= 3) {
2306 if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2308 data->inventorylist_options.slotborder = true;
2311 if (parts.size() >= 5) {
2312 video::SColor tmp_color;
2314 if (parseColorString(parts[3], tmp_color, false))
2315 m_default_tooltip_bgcolor = tmp_color;
2316 if (parseColorString(parts[4], tmp_color, false))
2317 m_default_tooltip_color = tmp_color;
2320 // update all already parsed inventorylists
2321 for (GUIInventoryList *e : m_inventorylists) {
2322 e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2323 data->inventorylist_options.slotbg_h);
2324 e->setSlotBorders(data->inventorylist_options.slotborder,
2325 data->inventorylist_options.slotbordercolor);
2329 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2331 std::vector<std::string> parts;
2332 if (!precheckElement("tooltip", element, 2, 5, parts))
2335 // Get mode and check size
2336 bool rect_mode = parts[0].find(',') != std::string::npos;
2337 size_t base_size = rect_mode ? 3 : 2;
2338 if (parts.size() != base_size && parts.size() != base_size + 2) {
2339 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2340 << element << "'" << std::endl;
2345 video::SColor bgcolor = m_default_tooltip_bgcolor;
2346 video::SColor color = m_default_tooltip_color;
2347 if (parts.size() == base_size + 2 &&
2348 (!parseColorString(parts[base_size], bgcolor, false) ||
2349 !parseColorString(parts[base_size + 1], color, false))) {
2350 errorstream << "Invalid color in tooltip element(" << parts.size()
2351 << "): '" << element << "'" << std::endl;
2355 // Make tooltip spec
2356 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2357 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2361 std::vector<std::string> v_pos = split(parts[0], ',');
2362 std::vector<std::string> v_geom = split(parts[1], ',');
2364 MY_CHECKPOS("tooltip", 0);
2365 MY_CHECKGEOM("tooltip", 1);
2370 if (data->real_coordinates) {
2371 pos = getRealCoordinateBasePos(v_pos);
2372 geom = getRealCoordinateGeometry(v_geom);
2374 pos = getElementBasePos(&v_pos);
2375 geom.X = stof(v_geom[0]) * spacing.X;
2376 geom.Y = stof(v_geom[1]) * spacing.Y;
2379 FieldSpec fieldspec(
2383 258 + m_fields.size()
2386 core::rect<s32> rect(pos, pos + geom);
2388 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2389 data->current_parent, fieldspec.fid, rect);
2391 // the element the rect tooltip is bound to should not block mouse-clicks
2392 e->setVisible(false);
2394 m_fields.push_back(fieldspec);
2395 m_tooltip_rects.emplace_back(e, spec);
2398 m_tooltips[parts[0]] = spec;
2402 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2408 std::vector<std::string> parts = split(data,'[');
2410 if (parts.size() < 2) {
2414 if (trim(parts[0]) != "formspec_version") {
2418 if (is_number(parts[1])) {
2419 m_formspec_version = mystoi(parts[1]);
2426 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2428 if (element.empty())
2431 std::vector<std::string> parts = split(element,'[');
2433 if (parts.size() < 2)
2436 std::string type = trim(parts[0]);
2437 std::string description = trim(parts[1]);
2439 if (type != "size" && type != "invsize")
2442 if (type == "invsize")
2443 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2445 parseSize(data, description);
2450 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2452 if (element.empty())
2455 std::vector<std::string> parts = split(element, '[');
2457 if (parts.size() != 2)
2460 std::string type = trim(parts[0]);
2461 std::string description = trim(parts[1]);
2463 if (type != "position")
2466 parsePosition(data, description);
2471 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2473 std::vector<std::string> parts = split(element, ';');
2475 if (parts.size() == 1 ||
2476 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2477 std::vector<std::string> v_geom = split(parts[0], ',');
2479 MY_CHECKGEOM("position", 0);
2481 data->offset.X = stof(v_geom[0]);
2482 data->offset.Y = stof(v_geom[1]);
2486 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2489 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2491 if (element.empty())
2494 std::vector<std::string> parts = split(element, '[');
2496 if (parts.size() != 2)
2499 std::string type = trim(parts[0]);
2500 std::string description = trim(parts[1]);
2502 if (type != "anchor")
2505 parseAnchor(data, description);
2510 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2512 std::vector<std::string> parts = split(element, ';');
2514 if (parts.size() == 1 ||
2515 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2516 std::vector<std::string> v_geom = split(parts[0], ',');
2518 MY_CHECKGEOM("anchor", 0);
2520 data->anchor.X = stof(v_geom[0]);
2521 data->anchor.Y = stof(v_geom[1]);
2525 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2526 << "'" << std::endl;
2529 bool GUIFormSpecMenu::parsePaddingDirect(parserData *data, const std::string &element)
2531 if (element.empty())
2534 std::vector<std::string> parts = split(element, '[');
2536 if (parts.size() != 2)
2539 std::string type = trim(parts[0]);
2540 std::string description = trim(parts[1]);
2542 if (type != "padding")
2545 parsePadding(data, description);
2550 void GUIFormSpecMenu::parsePadding(parserData *data, const std::string &element)
2552 std::vector<std::string> parts = split(element, ';');
2554 if (parts.size() == 1 ||
2555 (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
2556 std::vector<std::string> v_geom = split(parts[0], ',');
2558 MY_CHECKGEOM("padding", 0);
2560 data->padding.X = stof(v_geom[0]);
2561 data->padding.Y = stof(v_geom[1]);
2565 errorstream << "Invalid padding element (" << parts.size() << "): '" << element
2566 << "'" << std::endl;
2569 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2571 std::vector<std::string> parts = split(element, ';');
2573 if (parts.size() < 2) {
2574 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2575 << "'" << std::endl;
2582 for (size_t i = 1; i < parts.size(); i++) {
2583 size_t equal_pos = parts[i].find('=');
2584 if (equal_pos == std::string::npos) {
2585 errorstream << "Invalid style element (Property missing value): '" << element
2586 << "'" << std::endl;
2590 std::string propname = trim(parts[i].substr(0, equal_pos));
2591 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2593 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2595 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2596 if (prop == StyleSpec::NONE) {
2597 if (property_warned.find(propname) != property_warned.end()) {
2598 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2600 << "'" << std::endl;
2601 property_warned.insert(propname);
2606 spec.set(prop, value);
2609 std::vector<std::string> selectors = split(parts[0], ',');
2610 for (size_t sel = 0; sel < selectors.size(); sel++) {
2611 std::string selector = trim(selectors[sel]);
2613 // Copy the style properties to a new StyleSpec
2614 // This allows a separate state mask per-selector
2615 StyleSpec selector_spec = spec;
2617 // Parse state information, if it exists
2618 bool state_valid = true;
2619 size_t state_pos = selector.find(':');
2620 if (state_pos != std::string::npos) {
2621 std::string state_str = selector.substr(state_pos + 1);
2622 selector = selector.substr(0, state_pos);
2624 if (state_str.empty()) {
2625 errorstream << "Invalid style element (Invalid state): '" << element
2626 << "'" << std::endl;
2627 state_valid = false;
2629 std::vector<std::string> states = split(state_str, '+');
2630 for (std::string &state : states) {
2631 StyleSpec::State converted = StyleSpec::getStateByName(state);
2632 if (converted == StyleSpec::STATE_INVALID) {
2633 infostream << "Unknown style state " << state <<
2634 " in element '" << element << "'" << std::endl;
2635 state_valid = false;
2639 selector_spec.addState(converted);
2645 // Skip this selector
2650 theme_by_type[selector].push_back(selector_spec);
2652 theme_by_name[selector].push_back(selector_spec);
2655 // Backwards-compatibility for existing _hovered/_pressed properties
2656 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2657 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2658 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2659 StyleSpec hover_spec;
2660 hover_spec.addState(StyleSpec::STATE_HOVERED);
2662 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2663 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2665 if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2666 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2668 if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2669 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2673 theme_by_type[selector].push_back(hover_spec);
2675 theme_by_name[selector].push_back(hover_spec);
2678 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2679 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2680 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2681 StyleSpec press_spec;
2682 press_spec.addState(StyleSpec::STATE_PRESSED);
2684 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2685 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2687 if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2688 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2690 if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2691 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2695 theme_by_type[selector].push_back(press_spec);
2697 theme_by_name[selector].push_back(press_spec);
2705 void GUIFormSpecMenu::parseSetFocus(const std::string &element)
2707 std::vector<std::string> parts;
2708 if (!precheckElement("set_focus", element, 1, 2, parts))
2711 if (m_is_form_regenerated)
2712 return; // Never focus on resizing
2714 bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
2715 if (force_focus || m_text_dst->m_formname != m_last_formname)
2719 void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element)
2721 MY_CHECKCLIENT("model");
2723 std::vector<std::string> parts;
2724 if (!precheckElement("model", element, 5, 10, parts))
2727 // Avoid length checks by resizing
2728 if (parts.size() < 10)
2731 std::vector<std::string> v_pos = split(parts[0], ',');
2732 std::vector<std::string> v_geom = split(parts[1], ',');
2733 std::string name = unescape_string(parts[2]);
2734 std::string meshstr = unescape_string(parts[3]);
2735 std::vector<std::string> textures = split(parts[4], ',');
2736 std::vector<std::string> vec_rot = split(parts[5], ',');
2737 bool inf_rotation = is_yes(parts[6]);
2738 bool mousectrl = is_yes(parts[7]) || parts[7].empty(); // default true
2739 std::vector<std::string> frame_loop = split(parts[8], ',');
2740 std::string speed = unescape_string(parts[9]);
2742 MY_CHECKPOS("model", 0);
2743 MY_CHECKGEOM("model", 1);
2748 if (data->real_coordinates) {
2749 pos = getRealCoordinateBasePos(v_pos);
2750 geom = getRealCoordinateGeometry(v_geom);
2752 pos = getElementBasePos(&v_pos);
2753 geom.X = stof(v_geom[0]) * (float)imgsize.X;
2754 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
2757 if (!data->explicit_size)
2758 warningstream << "invalid use of model without a size[] element" << std::endl;
2760 scene::IAnimatedMesh *mesh = m_client->getMesh(meshstr);
2763 errorstream << "Invalid model element: Unable to load mesh:"
2764 << std::endl << "\t" << meshstr << std::endl;
2772 258 + m_fields.size()
2775 core::rect<s32> rect(pos, pos + geom);
2777 GUIScene *e = new GUIScene(Environment, m_client->getSceneManager(),
2778 data->current_parent, rect, spec.fid);
2780 auto meshnode = e->setMesh(mesh);
2782 for (u32 i = 0; i < textures.size() && i < meshnode->getMaterialCount(); ++i)
2783 e->setTexture(i, m_tsrc->getTexture(unescape_string(textures[i])));
2785 if (vec_rot.size() >= 2)
2786 e->setRotation(v2f(stof(vec_rot[0]), stof(vec_rot[1])));
2788 e->enableContinuousRotation(inf_rotation);
2789 e->enableMouseControl(mousectrl);
2791 s32 frame_loop_begin = 0;
2792 s32 frame_loop_end = 0x7FFFFFFF;
2794 if (frame_loop.size() == 2) {
2795 frame_loop_begin = stoi(frame_loop[0]);
2796 frame_loop_end = stoi(frame_loop[1]);
2799 e->setFrameLoop(frame_loop_begin, frame_loop_end);
2800 e->setAnimationSpeed(stof(speed));
2802 auto style = getStyleForElement("model", spec.fname);
2803 e->setStyles(style);
2806 m_fields.push_back(spec);
2809 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2812 if (element.empty())
2815 if (parseVersionDirect(element))
2818 size_t pos = element.find('[');
2819 if (pos == std::string::npos)
2822 std::string type = trim(element.substr(0, pos));
2823 std::string description = element.substr(pos+1);
2825 if (type == "container") {
2826 parseContainer(data, description);
2830 if (type == "container_end") {
2831 parseContainerEnd(data);
2835 if (type == "list") {
2836 parseList(data, description);
2840 if (type == "listring") {
2841 parseListRing(data, description);
2845 if (type == "checkbox") {
2846 parseCheckbox(data, description);
2850 if (type == "image") {
2851 parseImage(data, description);
2855 if (type == "animated_image") {
2856 parseAnimatedImage(data, description);
2860 if (type == "item_image") {
2861 parseItemImage(data, description);
2865 if (type == "button" || type == "button_exit") {
2866 parseButton(data, description, type);
2870 if (type == "background" || type == "background9") {
2871 parseBackground(data, description);
2875 if (type == "tableoptions"){
2876 parseTableOptions(data,description);
2880 if (type == "tablecolumns"){
2881 parseTableColumns(data,description);
2885 if (type == "table"){
2886 parseTable(data,description);
2890 if (type == "textlist"){
2891 parseTextList(data,description);
2895 if (type == "dropdown"){
2896 parseDropDown(data,description);
2900 if (type == "field_close_on_enter") {
2901 parseFieldCloseOnEnter(data, description);
2905 if (type == "pwdfield") {
2906 parsePwdField(data,description);
2910 if ((type == "field") || (type == "textarea")){
2911 parseField(data,description,type);
2915 if (type == "hypertext") {
2916 parseHyperText(data,description);
2920 if (type == "label") {
2921 parseLabel(data,description);
2925 if (type == "vertlabel") {
2926 parseVertLabel(data,description);
2930 if (type == "item_image_button") {
2931 parseItemImageButton(data,description);
2935 if ((type == "image_button") || (type == "image_button_exit")) {
2936 parseImageButton(data,description,type);
2940 if (type == "tabheader") {
2941 parseTabHeader(data,description);
2945 if (type == "box") {
2946 parseBox(data,description);
2950 if (type == "bgcolor") {
2951 parseBackgroundColor(data,description);
2955 if (type == "listcolors") {
2956 parseListColors(data,description);
2960 if (type == "tooltip") {
2961 parseTooltip(data,description);
2965 if (type == "scrollbar") {
2966 parseScrollBar(data, description);
2970 if (type == "real_coordinates") {
2971 data->real_coordinates = is_yes(description);
2975 if (type == "style") {
2976 parseStyle(data, description, false);
2980 if (type == "style_type") {
2981 parseStyle(data, description, true);
2985 if (type == "scrollbaroptions") {
2986 parseScrollBarOptions(data, description);
2990 if (type == "scroll_container") {
2991 parseScrollContainer(data, description);
2995 if (type == "scroll_container_end") {
2996 parseScrollContainerEnd(data);
3000 if (type == "set_focus") {
3001 parseSetFocus(description);
3005 if (type == "model") {
3006 parseModel(data, description);
3011 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
3015 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
3017 // Useless to regenerate without a screensize
3018 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
3024 // Preserve stuff only on same form, not on a new form.
3025 if (m_text_dst->m_formname == m_last_formname) {
3026 // Preserve tables/textlists
3027 for (auto &m_table : m_tables) {
3028 std::string tablename = m_table.first.fname;
3029 GUITable *table = m_table.second;
3030 mydata.table_dyndata[tablename] = table->getDynamicData();
3034 gui::IGUIElement *focused_element = Environment->getFocus();
3035 if (focused_element && focused_element->getParent() == this) {
3036 s32 focused_id = focused_element->getID();
3037 if (focused_id > 257) {
3038 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
3039 if (field.fid == focused_id) {
3040 m_focused_element = field.fname;
3047 // Don't keep old focus value
3048 m_focused_element = "";
3054 for (auto &table_it : m_tables)
3055 table_it.second->drop();
3056 for (auto &inventorylist_it : m_inventorylists)
3057 inventorylist_it->drop();
3058 for (auto &checkbox_it : m_checkboxes)
3059 checkbox_it.second->drop();
3060 for (auto &scrollbar_it : m_scrollbars)
3061 scrollbar_it.second->drop();
3062 for (auto &background_it : m_backgrounds)
3063 background_it->drop();
3064 for (auto &tooltip_rect_it : m_tooltip_rects)
3065 tooltip_rect_it.first->drop();
3066 for (auto &clickthrough_it : m_clickthrough_elements)
3067 clickthrough_it->drop();
3068 for (auto &scroll_container_it : m_scroll_containers)
3069 scroll_container_it.second->drop();
3071 mydata.size = v2s32(100, 100);
3072 mydata.screensize = screensize;
3073 mydata.offset = v2f32(0.5f, 0.5f);
3074 mydata.anchor = v2f32(0.5f, 0.5f);
3075 mydata.padding = v2f32(0.05f, 0.05f);
3076 mydata.simple_field_count = 0;
3078 // Base position of contents of form
3079 mydata.basepos = getBasePos();
3081 // the parent for the parsed elements
3082 mydata.current_parent = this;
3084 m_inventorylists.clear();
3085 m_backgrounds.clear();
3087 m_checkboxes.clear();
3088 m_scrollbars.clear();
3091 m_tooltip_rects.clear();
3092 m_inventory_rings.clear();
3093 m_dropdowns.clear();
3094 m_scroll_containers.clear();
3095 theme_by_name.clear();
3096 theme_by_type.clear();
3097 m_clickthrough_elements.clear();
3098 field_close_on_enter.clear();
3099 m_dropdown_index_event.clear();
3101 m_bgnonfullscreen = true;
3102 m_bgfullscreen = false;
3104 m_formspec_version = 1;
3107 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
3108 m_bgcolor = video::SColor(
3109 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
3110 clamp_u8(myround(formspec_bgcolor.X)),
3111 clamp_u8(myround(formspec_bgcolor.Y)),
3112 clamp_u8(myround(formspec_bgcolor.Z))
3117 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
3118 m_fullscreen_bgcolor = video::SColor(
3119 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
3120 clamp_u8(myround(formspec_bgcolor.X)),
3121 clamp_u8(myround(formspec_bgcolor.Y)),
3122 clamp_u8(myround(formspec_bgcolor.Z))
3126 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
3127 m_default_tooltip_color = video::SColor(255,255,255,255);
3131 assert(!m_tooltip_element);
3132 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
3133 m_tooltip_element = gui::StaticText::add(Environment, L"",
3134 core::rect<s32>(0, 0, 110, 18));
3135 m_tooltip_element->enableOverrideColor(true);
3136 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
3137 m_tooltip_element->setDrawBackground(true);
3138 m_tooltip_element->setDrawBorder(true);
3139 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
3140 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
3141 m_tooltip_element->setWordWrap(false);
3142 //we're not parent so no autograb for this one!
3143 m_tooltip_element->grab();
3146 std::vector<std::string> elements = split(m_formspec_string,']');
3149 /* try to read version from first element only */
3150 if (!elements.empty()) {
3151 if (parseVersionDirect(elements[0])) {
3156 /* we need size first in order to calculate image scale */
3157 mydata.explicit_size = false;
3158 for (; i< elements.size(); i++) {
3159 if (!parseSizeDirect(&mydata, elements[i])) {
3164 /* "position" element is always after "size" element if it used */
3165 for (; i< elements.size(); i++) {
3166 if (!parsePositionDirect(&mydata, elements[i])) {
3171 /* "anchor" element is always after "position" (or "size" element) if it used */
3172 for (; i< elements.size(); i++) {
3173 if (!parseAnchorDirect(&mydata, elements[i])) {
3178 /* "padding" element is always after "anchor" and previous if it is used */
3179 for (; i < elements.size(); i++) {
3180 if (!parsePaddingDirect(&mydata, elements[i])) {
3185 /* "no_prepend" element is always after "padding" and previous if it used */
3186 bool enable_prepends = true;
3187 for (; i < elements.size(); i++) {
3188 if (elements[i].empty())
3191 std::vector<std::string> parts = split(elements[i], '[');
3192 if (trim(parts[0]) == "no_prepend")
3193 enable_prepends = false;
3198 /* Copy of the "real_coordinates" element for after the form size. */
3199 mydata.real_coordinates = m_formspec_version >= 2;
3200 for (; i < elements.size(); i++) {
3201 std::vector<std::string> parts = split(elements[i], '[');
3202 std::string name = trim(parts[0]);
3203 if (name != "real_coordinates" || parts.size() != 2)
3204 break; // Invalid format
3206 mydata.real_coordinates = is_yes(trim(parts[1]));
3209 if (mydata.explicit_size) {
3210 // compute scaling for specified form size
3212 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3213 v2u32 delta = current_screensize - m_lockscreensize;
3215 if (current_screensize.Y > m_lockscreensize.Y)
3220 if (current_screensize.X > m_lockscreensize.X)
3225 offset = v2s32(delta.X,delta.Y);
3227 mydata.screensize = m_lockscreensize;
3229 offset = v2s32(0,0);
3232 double gui_scaling = g_settings->getFloat("gui_scaling");
3233 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3237 // In fixed-size mode, inventory image size
3238 // is 0.53 inch multiplied by the gui_scaling
3239 // config parameter. This magic size is chosen
3240 // to make the main menu (15.5 inventory images
3241 // wide, including border) just fit into the
3242 // default window (800 pixels wide) at 96 DPI
3243 // and default scaling (1.00).
3244 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3246 // Variables for the maximum imgsize that can fit in the screen.
3247 double fitx_imgsize;
3248 double fity_imgsize;
3250 v2f padded_screensize(
3251 mydata.screensize.X * (1.0f - mydata.padding.X * 2.0f),
3252 mydata.screensize.Y * (1.0f - mydata.padding.Y * 2.0f)
3255 if (mydata.real_coordinates) {
3256 fitx_imgsize = padded_screensize.X / mydata.invsize.X;
3257 fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
3259 // The maximum imgsize in the old coordinate system also needs to
3260 // factor in padding and spacing along with 0.1 inventory slot spare
3261 // and help text space, hence the magic numbers.
3262 fitx_imgsize = padded_screensize.X /
3263 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3264 fity_imgsize = padded_screensize.Y /
3265 ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
3268 s32 min_screen_dim = std::min(padded_screensize.X, padded_screensize.Y);
3270 #ifdef HAVE_TOUCHSCREENGUI
3271 // In Android, the preferred imgsize should be larger to accommodate the
3272 // smaller screensize.
3273 double prefer_imgsize = min_screen_dim / 10 * gui_scaling;
3275 // Desktop computers have more space, so try to fit 15 coordinates.
3276 double prefer_imgsize = min_screen_dim / 15 * gui_scaling;
3278 // Try to use the preferred imgsize, but if that's bigger than the maximum
3279 // size, use the maximum size.
3280 use_imgsize = std::min(prefer_imgsize,
3281 std::min(fitx_imgsize, fity_imgsize));
3284 // Everything else is scaled in proportion to the
3285 // inventory image size. The inventory slot spacing
3286 // is 5/4 image size horizontally and 15/13 image size
3287 // vertically. The padding around the form (incorporating
3288 // the border of the outer inventory slots) is 3/8
3289 // image size. Font height (baseline to baseline)
3290 // is 2/5 vertical inventory slot spacing, and button
3291 // half-height is 7/8 of font height.
3292 imgsize = v2s32(use_imgsize, use_imgsize);
3293 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3294 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3295 m_btn_height = use_imgsize*15.0/13 * 0.35;
3297 m_font = g_fontengine->getFont();
3299 if (mydata.real_coordinates) {
3300 mydata.size = v2s32(
3301 mydata.invsize.X*imgsize.X,
3302 mydata.invsize.Y*imgsize.Y
3305 mydata.size = v2s32(
3306 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3307 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3311 DesiredRect = mydata.rect = core::rect<s32>(
3312 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3313 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3314 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3315 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3318 // Non-size[] form must consist only of text fields and
3319 // implicit "Proceed" button. Use default font, and
3320 // temporary form size which will be recalculated below.
3321 m_font = g_fontengine->getFont();
3322 m_btn_height = font_line_height(m_font) * 0.875;
3323 DesiredRect = core::rect<s32>(
3324 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3325 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3326 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3327 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3330 recalculateAbsolutePosition(false);
3331 mydata.basepos = getBasePos();
3332 m_tooltip_element->setOverrideFont(m_font);
3334 gui::IGUISkin *skin = Environment->getSkin();
3336 gui::IGUIFont *old_font = skin->getFont();
3337 skin->setFont(m_font);
3339 pos_offset = v2f32();
3341 // used for formspec versions < 3
3342 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3344 if (enable_prepends) {
3345 // Backup the coordinates so that prepends can use the coordinates of choice.
3346 bool rc_backup = mydata.real_coordinates;
3347 u16 version_backup = m_formspec_version;
3348 mydata.real_coordinates = false; // Old coordinates by default.
3350 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3351 for (const auto &element : prepend_elements)
3352 parseElement(&mydata, element);
3354 // legacy sorting for formspec versions < 3
3355 if (m_formspec_version >= 3)
3356 // prepends do not need to be reordered
3357 legacy_sort_start = Children.getLast();
3358 else if (version_backup >= 3)
3359 // only prepends elements have to be reordered
3360 legacySortElements(legacy_sort_start);
3362 m_formspec_version = version_backup;
3363 mydata.real_coordinates = rc_backup; // Restore coordinates
3366 for (; i< elements.size(); i++) {
3367 parseElement(&mydata, elements[i]);
3370 if (mydata.current_parent != this) {
3371 errorstream << "Invalid formspec string: scroll_container was never closed!"
3373 } else if (!container_stack.empty()) {
3374 errorstream << "Invalid formspec string: container was never closed!"
3378 // get the scrollbar elements for scroll_containers
3379 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3380 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3381 if (c.first == b.first.fname) {
3382 c.second->setScrollBar(b.second);
3388 // If there are fields without explicit size[], add a "Proceed"
3389 // button and adjust size to fit all the fields.
3390 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3391 mydata.rect = core::rect<s32>(
3392 mydata.screensize.X / 2 - 580 / 2,
3393 mydata.screensize.Y / 2 - 300 / 2,
3394 mydata.screensize.X / 2 + 580 / 2,
3395 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3398 DesiredRect = mydata.rect;
3399 recalculateAbsolutePosition(false);
3400 mydata.basepos = getBasePos();
3403 v2s32 pos = mydata.basepos;
3404 pos.Y = (mydata.simple_field_count + 2) * 60;
3406 v2s32 size = DesiredRect.getSize();
3407 mydata.rect = core::rect<s32>(
3408 size.X / 2 - 70, pos.Y,
3409 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3411 const wchar_t *text = wgettext("Proceed");
3412 GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3417 // Set initial focus if parser didn't set it
3418 gui::IGUIElement *focused_element = Environment->getFocus();
3419 if (!focused_element
3420 || !isMyChild(focused_element)
3421 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3424 skin->setFont(old_font);
3427 if (m_formspec_version < 3)
3428 legacySortElements(legacy_sort_start);
3430 // Formname and regeneration setting
3431 if (!m_is_form_regenerated) {
3432 // Only set previous form name if we purposefully showed a new formspec
3433 m_last_formname = m_text_dst->m_formname;
3434 m_is_form_regenerated = true;
3438 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3441 Draw order for formspec_version <= 2:
3445 0 All other elements
3447 2 item_image, item_image_button
3452 if (from == Children.end())
3453 from = Children.begin();
3457 core::list<IGUIElement *>::Iterator to = Children.end();
3458 // 1: Copy into a sortable container
3459 std::vector<IGUIElement *> elements;
3460 for (auto it = from; it != to; ++it)
3461 elements.emplace_back(*it);
3463 // 2: Sort the container
3464 std::stable_sort(elements.begin(), elements.end(),
3465 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3466 const FieldSpec *spec_a = getSpecByID(a->getID());
3467 const FieldSpec *spec_b = getSpecByID(b->getID());
3468 return spec_a && spec_b &&
3469 spec_a->priority < spec_b->priority;
3472 // 3: Re-assign the pointers
3473 for (auto e : elements) {
3480 bool GUIFormSpecMenu::getAndroidUIInput()
3482 if (!hasAndroidUIInput())
3486 if (porting::getInputDialogState() == -1)
3489 std::string fieldname = m_jni_field_name;
3490 m_jni_field_name.clear();
3492 for (const FieldSpec &field : m_fields) {
3493 if (field.fname != fieldname)
3496 IGUIElement *element = getElementFromId(field.fid, true);
3498 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3501 std::string text = porting::getInputDialogValue();
3502 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3508 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3510 for (const GUIInventoryList *e : m_inventorylists) {
3511 s32 item_index = e->getItemIndexAtPos(p);
3512 if (item_index != -1)
3513 return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3517 return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3520 void GUIFormSpecMenu::drawSelectedItem()
3522 video::IVideoDriver* driver = Environment->getVideoDriver();
3524 if (!m_selected_item) {
3525 // reset rotation time
3526 drawItemStack(driver, m_font, ItemStack(),
3527 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3528 m_client, IT_ROT_DRAGGED);
3532 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3534 InventoryList *list = inv->getList(m_selected_item->listname);
3536 ItemStack stack = list->getItem(m_selected_item->i);
3537 stack.count = m_selected_amount;
3539 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3540 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3541 rect.constrainTo(driver->getViewPort());
3542 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3545 void GUIFormSpecMenu::drawMenu()
3548 const std::string &newform = m_form_src->getForm();
3549 if (newform != m_formspec_string) {
3550 m_formspec_string = newform;
3551 m_is_form_regenerated = false;
3552 regenerateGui(m_screensize_old);
3556 gui::IGUISkin* skin = Environment->getSkin();
3557 sanity_check(skin != NULL);
3558 gui::IGUIFont *old_font = skin->getFont();
3559 skin->setFont(m_font);
3561 m_hovered_item_tooltips.clear();
3563 updateSelectedItem();
3565 video::IVideoDriver* driver = Environment->getVideoDriver();
3568 Draw background color
3570 v2u32 screenSize = driver->getScreenSize();
3571 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3574 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3575 if (m_bgnonfullscreen)
3576 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3579 Draw rect_mode tooltip
3581 m_tooltip_element->setVisible(false);
3583 for (const auto &pair : m_tooltip_rects) {
3584 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3585 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3586 const std::wstring &text = pair.second.tooltip;
3587 if (!text.empty()) {
3588 showTooltip(text, pair.second.color, pair.second.bgcolor);
3597 for (gui::IGUIElement *e : m_backgrounds) {
3598 e->setVisible(true);
3600 e->setVisible(false);
3603 // Some elements are only visible while being drawn
3604 for (gui::IGUIElement *e : m_clickthrough_elements)
3605 e->setVisible(true);
3608 This is where all the drawing happens.
3610 core::list<IGUIElement*>::Iterator it = Children.begin();
3611 for (; it != Children.end(); ++it)
3612 if ((*it)->isNotClipped() ||
3613 AbsoluteClippingRect.isRectCollided(
3614 (*it)->getAbsolutePosition()))
3617 for (gui::IGUIElement *e : m_clickthrough_elements)
3618 e->setVisible(false);
3620 // Draw hovered item tooltips
3621 for (const std::string &tooltip : m_hovered_item_tooltips) {
3622 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3623 m_default_tooltip_bgcolor);
3626 if (m_hovered_item_tooltips.empty()) {
3627 // reset rotation time
3628 drawItemStack(driver, m_font, ItemStack(),
3629 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3630 NULL, m_client, IT_ROT_HOVERED);
3633 /* TODO find way to show tooltips on touchscreen */
3634 #ifndef HAVE_TOUCHSCREENGUI
3635 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3639 Draw fields/buttons tooltips and update the mouse cursor
3641 gui::IGUIElement *hovered =
3642 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3644 #ifndef HAVE_TOUCHSCREENGUI
3645 gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3647 gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3649 bool hovered_element_found = false;
3651 if (hovered != NULL) {
3653 core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3654 driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3657 s32 id = hovered->getID();
3660 m_old_tooltip_id = id;
3662 if (id == m_old_tooltip_id) {
3663 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3665 m_hovered_time = porting::getTimeMs();
3666 m_old_tooltip_id = id;
3670 // Find and update the current tooltip and cursor icon
3672 for (const FieldSpec &field : m_fields) {
3674 if (field.fid != id)
3677 if (delta >= m_tooltip_show_delay) {
3678 const std::wstring &text = m_tooltips[field.fname].tooltip;
3680 showTooltip(text, m_tooltips[field.fname].color,
3681 m_tooltips[field.fname].bgcolor);
3684 #ifndef HAVE_TOUCHSCREENGUI
3685 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3686 current_cursor_icon != field.fcursor_icon)
3687 cursor_control->setActiveIcon(field.fcursor_icon);
3690 hovered_element_found = true;
3697 if (!hovered_element_found) {
3698 // no element is hovered
3699 #ifndef HAVE_TOUCHSCREENGUI
3700 if (current_cursor_icon != ECI_NORMAL)
3701 cursor_control->setActiveIcon(ECI_NORMAL);
3705 m_tooltip_element->draw();
3708 Draw dragged item stack
3712 skin->setFont(old_font);
3716 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3717 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3719 EnrichedString ntext(text);
3720 ntext.setDefaultColor(color);
3721 if (!ntext.hasBackground())
3722 ntext.setBackground(bgcolor);
3724 setStaticText(m_tooltip_element, ntext);
3726 // Tooltip size and offset
3727 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3728 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3730 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3731 int tooltip_offset_x = m_btn_height;
3732 int tooltip_offset_y = m_btn_height;
3733 #ifdef HAVE_TOUCHSCREENGUI
3734 tooltip_offset_x *= 3;
3735 tooltip_offset_y = 0;
3736 if (m_pointer.X > (s32)screenSize.X / 2)
3737 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3739 // Hide tooltip after ETIE_LEFT_UP
3740 if (m_pointer.X == 0)
3744 // Calculate and set the tooltip position
3745 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3746 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3747 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3748 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3749 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3750 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3752 m_tooltip_element->setRelativePosition(
3754 core::position2d<s32>(tooltip_x, tooltip_y),
3755 core::dimension2d<s32>(tooltip_width, tooltip_height)
3759 // Display the tooltip
3760 m_tooltip_element->setVisible(true);
3761 bringToFront(m_tooltip_element);
3764 void GUIFormSpecMenu::updateSelectedItem()
3766 verifySelectedItem();
3768 // If craftresult is nonempty and nothing else is selected, select it now.
3769 if (!m_selected_item) {
3770 for (const GUIInventoryList *e : m_inventorylists) {
3771 if (e->getListname() != "craftpreview")
3774 Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3778 InventoryList *list = inv->getList("craftresult");
3780 if (!list || list->getSize() == 0)
3783 const ItemStack &item = list->getItem(0);
3787 // Grab selected item from the crafting result list
3788 m_selected_item = new GUIInventoryList::ItemSpec;
3789 m_selected_item->inventoryloc = e->getInventoryloc();
3790 m_selected_item->listname = "craftresult";
3791 m_selected_item->i = 0;
3792 m_selected_amount = item.count;
3793 m_selected_dragging = false;
3798 // If craftresult is selected, keep the whole stack selected
3799 if (m_selected_item && m_selected_item->listname == "craftresult")
3800 m_selected_amount = verifySelectedItem().count;
3803 ItemStack GUIFormSpecMenu::verifySelectedItem()
3805 // If the selected stack has become empty for some reason, deselect it.
3806 // If the selected stack has become inaccessible, deselect it.
3807 // If the selected stack has become smaller, adjust m_selected_amount.
3808 // Return the selected stack.
3810 if (m_selected_item) {
3811 if (m_selected_item->isValid()) {
3812 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3814 InventoryList *list = inv->getList(m_selected_item->listname);
3815 if (list && (u32) m_selected_item->i < list->getSize()) {
3816 ItemStack stack = list->getItem(m_selected_item->i);
3817 if (!m_selected_swap.empty()) {
3818 if (m_selected_swap.name == stack.name &&
3819 m_selected_swap.count == stack.count)
3820 m_selected_swap.clear();
3822 m_selected_amount = std::min(m_selected_amount, stack.count);
3831 // selection was not valid
3832 delete m_selected_item;
3833 m_selected_item = nullptr;
3834 m_selected_amount = 0;
3835 m_selected_dragging = false;
3840 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
3846 if (quitmode == quit_mode_accept) {
3847 fields["quit"] = "true";
3850 if (quitmode == quit_mode_cancel) {
3851 fields["quit"] = "true";
3852 m_text_dst->gotText(fields);
3856 if (current_keys_pending.key_down) {
3857 fields["key_down"] = "true";
3858 current_keys_pending.key_down = false;
3861 if (current_keys_pending.key_up) {
3862 fields["key_up"] = "true";
3863 current_keys_pending.key_up = false;
3866 if (current_keys_pending.key_enter) {
3867 fields["key_enter"] = "true";
3868 current_keys_pending.key_enter = false;
3871 if (!current_field_enter_pending.empty()) {
3872 fields["key_enter_field"] = current_field_enter_pending;
3873 current_field_enter_pending = "";
3876 if (current_keys_pending.key_escape) {
3877 fields["key_escape"] = "true";
3878 current_keys_pending.key_escape = false;
3881 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3883 std::string name = s.fname;
3884 if (s.ftype == f_Button) {
3885 fields[name] = wide_to_utf8(s.flabel);
3886 } else if (s.ftype == f_Table) {
3887 GUITable *table = getTable(s.fname);
3889 fields[name] = table->checkEvent();
3891 } else if (s.ftype == f_DropDown) {
3892 // No dynamic cast possible due to some distributions shipped
3893 // without rtti support in Irrlicht
3894 IGUIElement *element = getElementFromId(s.fid, true);
3895 gui::IGUIComboBox *e = NULL;
3896 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3897 e = static_cast<gui::IGUIComboBox *>(element);
3899 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3900 << "field without dropdown element" << std::endl;
3903 s32 selected = e->getSelected();
3904 if (selected >= 0) {
3905 if (m_dropdown_index_event.find(s.fname) !=
3906 m_dropdown_index_event.end()) {
3907 fields[name] = std::to_string(selected + 1);
3909 std::vector<std::string> *dropdown_values =
3910 getDropDownValues(s.fname);
3911 if (dropdown_values && selected < (s32)dropdown_values->size())
3912 fields[name] = (*dropdown_values)[selected];
3915 } else if (s.ftype == f_TabHeader) {
3916 // No dynamic cast possible due to some distributions shipped
3917 // without rtti support in Irrlicht
3918 IGUIElement *element = getElementFromId(s.fid, true);
3919 gui::IGUITabControl *e = nullptr;
3920 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3921 e = static_cast<gui::IGUITabControl *>(element);
3925 fields[name] = itos(e->getActiveTab() + 1);
3927 } else if (s.ftype == f_CheckBox) {
3928 // No dynamic cast possible due to some distributions shipped
3929 // without rtti support in Irrlicht
3930 IGUIElement *element = getElementFromId(s.fid, true);
3931 gui::IGUICheckBox *e = nullptr;
3932 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3933 e = static_cast<gui::IGUICheckBox*>(element);
3938 fields[name] = "true";
3940 fields[name] = "false";
3942 } else if (s.ftype == f_ScrollBar) {
3943 // No dynamic cast possible due to some distributions shipped
3944 // without rtti support in Irrlicht
3945 IGUIElement *element = getElementFromId(s.fid, true);
3946 GUIScrollBar *e = nullptr;
3947 if (element && element->getType() == gui::EGUIET_ELEMENT)
3948 e = static_cast<GUIScrollBar *>(element);
3951 if (s.fdefault == L"Changed")
3952 fields[name] = "CHG:" + itos(e->getPos());
3954 fields[name] = "VAL:" + itos(e->getPos());
3956 } else if (s.ftype == f_AnimatedImage) {
3957 // No dynamic cast possible due to some distributions shipped
3958 // without rtti support in Irrlicht
3959 IGUIElement *element = getElementFromId(s.fid, true);
3960 GUIAnimatedImage *e = nullptr;
3961 if (element && element->getType() == gui::EGUIET_ELEMENT)
3962 e = static_cast<GUIAnimatedImage *>(element);
3965 fields[name] = std::to_string(e->getFrameIndex() + 1);
3967 IGUIElement *e = getElementFromId(s.fid, true);
3969 fields[name] = wide_to_utf8(e->getText());
3974 m_text_dst->gotText(fields);
3978 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3980 // The IGUITabControl renders visually using the skin's selected
3981 // font, which we override for the duration of form drawing,
3982 // but computes tab hotspots based on how it would have rendered
3983 // using the font that is selected at the time of button release.
3984 // To make these two consistent, temporarily override the skin's
3985 // font while the IGUITabControl is processing the event.
3986 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3987 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3988 s32 x = event.MouseInput.X;
3989 s32 y = event.MouseInput.Y;
3990 gui::IGUIElement *hovered =
3991 Environment->getRootGUIElement()->getElementFromPoint(
3992 core::position2d<s32>(x, y));
3993 if (hovered && isMyChild(hovered) &&
3994 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3995 gui::IGUISkin* skin = Environment->getSkin();
3996 sanity_check(skin != NULL);
3997 gui::IGUIFont *old_font = skin->getFont();
3998 skin->setFont(m_font);
3999 bool retval = hovered->OnEvent(event);
4000 skin->setFont(old_font);
4005 // Fix Esc/Return key being eaten by checkboxen and tables
4006 if (event.EventType == EET_KEY_INPUT_EVENT) {
4007 KeyPress kp(event.KeyInput);
4008 if (kp == EscapeKey || kp == CancelKey
4009 || kp == getKeySetting("keymap_inventory")
4010 || event.KeyInput.Key==KEY_RETURN) {
4011 gui::IGUIElement *focused = Environment->getFocus();
4012 if (focused && isMyChild(focused) &&
4013 (focused->getType() == gui::EGUIET_LIST_BOX ||
4014 focused->getType() == gui::EGUIET_CHECK_BOX) &&
4015 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
4016 event.KeyInput.Key != KEY_RETURN)) {
4022 // Mouse wheel and move events: send to hovered element instead of focused
4023 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4024 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
4025 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4026 event.MouseInput.ButtonStates == 0))) {
4027 s32 x = event.MouseInput.X;
4028 s32 y = event.MouseInput.Y;
4029 gui::IGUIElement *hovered =
4030 Environment->getRootGUIElement()->getElementFromPoint(
4031 core::position2d<s32>(x, y));
4032 if (hovered && isMyChild(hovered)) {
4033 hovered->OnEvent(event);
4034 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
4038 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
4039 /* TODO add a check like:
4040 if (event.JoystickEvent != joystick_we_listen_for)
4043 bool handled = m_joystick->handleEvent(event.JoystickEvent);
4045 if (m_joystick->wasKeyDown(KeyType::ESC)) {
4047 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
4049 acceptInput(quit_mode_accept);
4057 return GUIModalMenu::preprocessEvent(event);
4060 void GUIFormSpecMenu::tryClose()
4064 acceptInput(quit_mode_cancel);
4067 m_text_dst->gotText(L"MenuQuit");
4071 enum ButtonEventType : u8
4084 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
4086 if (event.EventType==EET_KEY_INPUT_EVENT) {
4087 KeyPress kp(event.KeyInput);
4088 if (event.KeyInput.PressedDown && (
4089 (kp == EscapeKey) || (kp == CancelKey) ||
4090 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4095 if (m_client != NULL && event.KeyInput.PressedDown &&
4096 (kp == getKeySetting("keymap_screenshot"))) {
4097 m_client->makeScreenshot();
4100 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4101 m_show_debug = !m_show_debug;
4103 if (event.KeyInput.PressedDown &&
4104 (event.KeyInput.Key==KEY_RETURN ||
4105 event.KeyInput.Key==KEY_UP ||
4106 event.KeyInput.Key==KEY_DOWN)
4108 switch (event.KeyInput.Key) {
4110 current_keys_pending.key_enter = true;
4113 current_keys_pending.key_up = true;
4116 current_keys_pending.key_down = true;
4120 //can't happen at all!
4121 FATAL_ERROR("Reached a source line that can't ever been reached");
4124 if (current_keys_pending.key_enter && m_allowclose) {
4125 acceptInput(quit_mode_accept);
4135 /* Mouse event other than movement, or crossing the border of inventory
4136 field while holding right mouse button
4138 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4139 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4140 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4141 event.MouseInput.isRightPressed() &&
4142 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4144 // Get selected item and hovered/clicked item (s)
4146 m_old_tooltip_id = -1;
4147 updateSelectedItem();
4148 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4150 Inventory *inv_selected = NULL;
4151 Inventory *inv_s = NULL;
4152 InventoryList *list_s = NULL;
4154 if (m_selected_item) {
4155 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4156 sanity_check(inv_selected);
4157 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4164 inv_s = m_invmgr->getInventory(s.inventoryloc);
4167 errorstream << "InventoryMenu: The selected inventory location "
4168 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4170 s.i = -1; // make it invalid again
4174 list_s = inv_s->getList(s.listname);
4175 if (list_s == NULL) {
4176 verbosestream << "InventoryMenu: The selected inventory list \""
4177 << s.listname << "\" does not exist" << std::endl;
4178 s.i = -1; // make it invalid again
4182 if ((u32)s.i >= list_s->getSize()) {
4183 infostream << "InventoryMenu: The selected inventory list \""
4184 << s.listname << "\" is too small (i=" << s.i << ", size="
4185 << list_s->getSize() << ")" << std::endl;
4186 s.i = -1; // make it invalid again
4190 s_count = list_s->getItem(s.i).count;
4193 bool identical = m_selected_item && s.isValid() &&
4194 (inv_selected == inv_s) &&
4195 (m_selected_item->listname == s.listname) &&
4196 (m_selected_item->i == s.i);
4198 ButtonEventType button = BET_LEFT;
4199 ButtonEventType updown = BET_OTHER;
4200 switch (event.MouseInput.Event) {
4201 case EMIE_LMOUSE_PRESSED_DOWN:
4202 button = BET_LEFT; updown = BET_DOWN;
4204 case EMIE_RMOUSE_PRESSED_DOWN:
4205 button = BET_RIGHT; updown = BET_DOWN;
4207 case EMIE_MMOUSE_PRESSED_DOWN:
4208 button = BET_MIDDLE; updown = BET_DOWN;
4210 case EMIE_MOUSE_WHEEL:
4211 button = (event.MouseInput.Wheel > 0) ?
4212 BET_WHEEL_UP : BET_WHEEL_DOWN;
4215 case EMIE_LMOUSE_LEFT_UP:
4216 button = BET_LEFT; updown = BET_UP;
4218 case EMIE_RMOUSE_LEFT_UP:
4219 button = BET_RIGHT; updown = BET_UP;
4221 case EMIE_MMOUSE_LEFT_UP:
4222 button = BET_MIDDLE; updown = BET_UP;
4224 case EMIE_MOUSE_MOVED:
4231 // Set this number to a positive value to generate a move action
4232 // from m_selected_item to s.
4233 u32 move_amount = 0;
4235 // Set this number to a positive value to generate a move action
4236 // from s to the next inventory ring.
4237 u32 shift_move_amount = 0;
4239 // Set this number to a positive value to generate a drop action
4240 // from m_selected_item.
4241 u32 drop_amount = 0;
4243 // Set this number to a positive value to generate a craft action at s.
4244 u32 craft_amount = 0;
4248 // Some mouse button has been pressed
4250 //infostream << "Mouse button " << button << " pressed at p=("
4251 // << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4254 m_selected_dragging = false;
4256 if (s.isValid() && s.listname == "craftpreview") {
4257 // Craft preview has been clicked: craft
4258 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4259 } else if (!m_selected_item) {
4260 if (s_count && button != BET_WHEEL_UP) {
4261 // Non-empty stack has been clicked: select or shift-move it
4262 m_selected_item = new GUIInventoryList::ItemSpec(s);
4265 if (button == BET_RIGHT)
4266 count = (s_count + 1) / 2;
4267 else if (button == BET_MIDDLE)
4268 count = MYMIN(s_count, 10);
4269 else if (button == BET_WHEEL_DOWN)
4274 if (!event.MouseInput.Shift) {
4275 // no shift: select item
4276 m_selected_amount = count;
4277 m_selected_dragging = button != BET_WHEEL_DOWN;
4278 m_auto_place = false;
4280 // shift pressed: move item, right click moves 1
4281 shift_move_amount = button == BET_RIGHT ? 1 : count;
4284 } else { // m_selected_item != NULL
4285 assert(m_selected_amount >= 1);
4288 // Clicked a slot: move
4289 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4291 else if (button == BET_MIDDLE)
4292 move_amount = MYMIN(m_selected_amount, 10);
4293 else if (button == BET_LEFT)
4294 move_amount = m_selected_amount;
4298 if (button == BET_WHEEL_DOWN) {
4299 if (m_selected_amount < s_count)
4300 ++m_selected_amount;
4302 if (move_amount >= m_selected_amount)
4303 m_selected_amount = 0;
4305 m_selected_amount -= move_amount;
4309 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4310 && button != BET_WHEEL_DOWN) {
4311 // Clicked outside of the window: drop
4312 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4314 else if (button == BET_MIDDLE)
4315 drop_amount = MYMIN(m_selected_amount, 10);
4317 drop_amount = m_selected_amount;
4322 // Some mouse button has been released
4324 //infostream<<"Mouse button "<<button<<" released at p=("
4325 // <<p.X<<","<<p.Y<<")"<<std::endl;
4327 if (m_selected_dragging && m_selected_item) {
4330 // Dragged to different slot: move all selected
4331 move_amount = m_selected_amount;
4333 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4334 // Dragged outside of window: drop all selected
4335 drop_amount = m_selected_amount;
4339 m_selected_dragging = false;
4340 // Keep track of whether the mouse button be released
4341 // One click is drag without dropping. Click + release
4342 // + click changes to drop item when moved mode
4343 if (m_selected_item)
4344 m_auto_place = true;
4347 // Mouse has been moved and rmb is down and mouse pointer just
4348 // entered a new inventory field (checked in the entry-if, this
4349 // is the only action here that is generated by mouse movement)
4350 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4352 // TODO: middle mouse to move 10 items might be handy
4354 // Only move an item if the destination slot is empty
4355 // or contains the same item type as what is going to be
4357 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4358 InventoryList *list_to = list_s;
4359 assert(list_from && list_to);
4360 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4361 ItemStack stack_to = list_to->getItem(s.i);
4362 if (stack_to.empty() || stack_to.name == stack_from.name)
4371 // Possibly send inventory action to server
4372 if (move_amount > 0) {
4373 // Send IAction::Move
4375 assert(m_selected_item && m_selected_item->isValid());
4376 assert(s.isValid());
4378 assert(inv_selected && inv_s);
4379 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4380 InventoryList *list_to = list_s;
4381 assert(list_from && list_to);
4382 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4383 ItemStack stack_to = list_to->getItem(s.i);
4385 // Check how many items can be moved
4386 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4387 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4389 // If source stack cannot be added to destination stack at all,
4391 if (leftover.count == stack_from.count &&
4392 leftover.name == stack_from.name) {
4394 if (m_selected_swap.empty()) {
4395 m_selected_amount = stack_to.count;
4396 m_selected_dragging = false;
4398 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4399 // Skip next validation checks due async inventory calls
4400 m_selected_swap = stack_to;
4405 // Source stack goes fully into destination stack
4406 else if (leftover.empty()) {
4407 m_selected_amount -= move_amount;
4409 // Source stack goes partly into destination stack
4411 move_amount -= leftover.count;
4412 m_selected_amount -= move_amount;
4416 infostream << "Handing IAction::Move to manager" << std::endl;
4417 IMoveAction *a = new IMoveAction();
4418 a->count = move_amount;
4419 a->from_inv = m_selected_item->inventoryloc;
4420 a->from_list = m_selected_item->listname;
4421 a->from_i = m_selected_item->i;
4422 a->to_inv = s.inventoryloc;
4423 a->to_list = s.listname;
4425 m_invmgr->inventoryAction(a);
4427 } else if (shift_move_amount > 0) {
4428 u32 mis = m_inventory_rings.size();
4430 for (; i < mis; i++) {
4431 const ListRingSpec &sp = m_inventory_rings[i];
4432 if (sp.inventoryloc == s.inventoryloc
4433 && sp.listname == s.listname)
4437 if (i >= mis) // if not found
4439 u32 to_inv_ind = (i + 1) % mis;
4440 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4441 InventoryList *list_from = list_s;
4444 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4447 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4450 ItemStack stack_from = list_from->getItem(s.i);
4451 assert(shift_move_amount <= stack_from.count);
4453 infostream << "Handing IAction::Move to manager" << std::endl;
4454 IMoveAction *a = new IMoveAction();
4455 a->count = shift_move_amount;
4456 a->from_inv = s.inventoryloc;
4457 a->from_list = s.listname;
4459 a->to_inv = to_inv_sp.inventoryloc;
4460 a->to_list = to_inv_sp.listname;
4461 a->move_somewhere = true;
4462 m_invmgr->inventoryAction(a);
4464 } else if (drop_amount > 0) {
4465 // Send IAction::Drop
4467 assert(m_selected_item && m_selected_item->isValid());
4468 assert(inv_selected);
4469 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4471 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4473 // Check how many items can be dropped
4474 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4475 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4476 m_selected_amount -= drop_amount;
4478 infostream << "Handing IAction::Drop to manager" << std::endl;
4479 IDropAction *a = new IDropAction();
4480 a->count = drop_amount;
4481 a->from_inv = m_selected_item->inventoryloc;
4482 a->from_list = m_selected_item->listname;
4483 a->from_i = m_selected_item->i;
4484 m_invmgr->inventoryAction(a);
4485 } else if (craft_amount > 0) {
4486 assert(s.isValid());
4488 // if there are no items selected or the selected item
4489 // belongs to craftresult list, proceed with crafting
4490 if (!m_selected_item ||
4491 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4495 // Send IACTION_CRAFT
4496 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4497 ICraftAction *a = new ICraftAction();
4498 a->count = craft_amount;
4499 a->craft_inv = s.inventoryloc;
4500 m_invmgr->inventoryAction(a);
4504 // If m_selected_amount has been decreased to zero, deselect
4505 if (m_selected_amount == 0) {
4506 m_selected_swap.clear();
4507 delete m_selected_item;
4508 m_selected_item = nullptr;
4509 m_selected_amount = 0;
4510 m_selected_dragging = false;
4512 m_old_pointer = m_pointer;
4515 if (event.EventType == EET_GUI_EVENT) {
4516 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4518 // find the element that was clicked
4519 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4520 if ((s.ftype == f_TabHeader) &&
4521 (s.fid == event.GUIEvent.Caller->getID())) {
4522 if (!s.sound.empty() && m_sound_manager)
4523 m_sound_manager->playSound(s.sound, false, 1.0f);
4531 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4533 if (!canTakeFocus(event.GUIEvent.Element)) {
4534 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4536 // Returning true disables focus change
4540 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4541 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4542 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4543 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4544 s32 caller_id = event.GUIEvent.Caller->getID();
4546 if (caller_id == 257) {
4548 acceptInput(quit_mode_accept);
4552 m_text_dst->gotText(L"ExitButton");
4554 // quitMenu deallocates menu
4558 // find the element that was clicked
4559 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4560 // if its a button, set the send field so
4561 // lua knows which button was pressed
4563 if (caller_id != s.fid)
4566 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4567 if (!s.sound.empty() && m_sound_manager)
4568 m_sound_manager->playSound(s.sound, false, 1.0f);
4573 acceptInput(quit_mode_accept);
4576 m_text_dst->gotText(L"ExitButton");
4581 acceptInput(quit_mode_no);
4585 } else if (s.ftype == f_DropDown) {
4586 // only send the changed dropdown
4587 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4588 if (s2.ftype == f_DropDown) {
4592 if (!s.sound.empty() && m_sound_manager)
4593 m_sound_manager->playSound(s.sound, false, 1.0f);
4595 acceptInput(quit_mode_no);
4597 // revert configuration to make sure dropdowns are sent on
4598 // regular button click
4599 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4600 if (s2.ftype == f_DropDown) {
4605 } else if (s.ftype == f_ScrollBar) {
4606 s.fdefault = L"Changed";
4607 acceptInput(quit_mode_no);
4609 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4610 if (!s.sound.empty() && m_sound_manager)
4611 m_sound_manager->playSound(s.sound, false, 1.0f);
4619 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4620 // move scroll_containers
4621 for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4622 c.second->onScrollEvent(event.GUIEvent.Caller);
4625 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4626 if (event.GUIEvent.Caller->getID() > 257) {
4627 bool close_on_enter = true;
4628 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4629 if (s.ftype == f_Unknown &&
4630 s.fid == event.GUIEvent.Caller->getID()) {
4631 current_field_enter_pending = s.fname;
4632 std::unordered_map<std::string, bool>::const_iterator it =
4633 field_close_on_enter.find(s.fname);
4634 if (it != field_close_on_enter.end())
4635 close_on_enter = (*it).second;
4641 if (m_allowclose && close_on_enter) {
4642 current_keys_pending.key_enter = true;
4643 acceptInput(quit_mode_accept);
4646 current_keys_pending.key_enter = true;
4649 // quitMenu deallocates menu
4654 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4655 int current_id = event.GUIEvent.Caller->getID();
4656 if (current_id > 257) {
4657 // find the element that was clicked
4658 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4659 // if it's a table, set the send field
4660 // so lua knows which table was changed
4661 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4672 return Parent ? Parent->OnEvent(event) : false;
4676 * get name of element by element id
4677 * @param id of element
4678 * @return name string or empty string
4680 std::string GUIFormSpecMenu::getNameByID(s32 id)
4682 for (FieldSpec &spec : m_fields) {
4690 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4692 for (FieldSpec &spec : m_fields) {
4700 * get label of element by id
4701 * @param id of element
4702 * @return label string or empty string
4704 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4706 for (FieldSpec &spec : m_fields) {
4713 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4714 const std::string &name, const std::string &parent_type) {
4715 return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4718 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4719 const std::string &type, const std::string &name, const std::string &parent_type)
4721 std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4723 auto it = theme_by_type.find("*");
4724 if (it != theme_by_type.end()) {
4725 for (const StyleSpec &spec : it->second)
4726 ret[(u32)spec.getState()] |= spec;
4729 it = theme_by_name.find("*");
4730 if (it != theme_by_name.end()) {
4731 for (const StyleSpec &spec : it->second)
4732 ret[(u32)spec.getState()] |= spec;
4735 if (!parent_type.empty()) {
4736 it = theme_by_type.find(parent_type);
4737 if (it != theme_by_type.end()) {
4738 for (const StyleSpec &spec : it->second)
4739 ret[(u32)spec.getState()] |= spec;
4743 it = theme_by_type.find(type);
4744 if (it != theme_by_type.end()) {
4745 for (const StyleSpec &spec : it->second)
4746 ret[(u32)spec.getState()] |= spec;
4749 it = theme_by_name.find(name);
4750 if (it != theme_by_name.end()) {
4751 for (const StyleSpec &spec : it->second)
4752 ret[(u32)spec.getState()] |= spec;