3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "guiFormSpecMenu.h"
27 #include "guiScrollBar.h"
29 #include "constants.h"
31 #include "client/keycode.h"
32 #include "util/strfnd.h"
33 #include <IGUIButton.h>
34 #include <IGUICheckBox.h>
35 #include <IGUIComboBox.h>
36 #include <IGUIEditBox.h>
37 #include <IGUIStaticText.h>
39 #include <IGUITabControl.h>
40 #include "client/renderingengine.h"
42 #include "client/tile.h" // ITextureSource
43 #include "client/hud.h" // drawItemStack
47 #include "scripting_server.h"
48 #include "mainmenumanager.h"
51 #include "client/client.h"
52 #include "client/fontengine.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "guiBackgroundImage.h"
60 #include "guiButton.h"
61 #include "guiEditBoxWithScrollbar.h"
62 #include "guiItemImage.h"
63 #include "guiScrollBar.h"
65 #include "intlGUIEditBox.h"
66 #include "guiHyperText.h"
68 #define MY_CHECKPOS(a,b) \
69 if (v_pos.size() != 2) { \
70 errorstream<< "Invalid pos for element " << a << "specified: \"" \
71 << parts[b] << "\"" << std::endl; \
75 #define MY_CHECKGEOM(a,b) \
76 if (v_geom.size() != 2) { \
77 errorstream<< "Invalid geometry for element " << a << \
78 "specified: \"" << parts[b] << "\"" << std::endl; \
84 static unsigned int font_line_height(gui::IGUIFont *font)
86 return font->getDimension(L"Ay").Height + font->getKerningHeight();
89 inline u32 clamp_u8(s32 value)
91 return (u32) MYMIN(MYMAX(value, 0), 255);
94 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
95 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
96 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
97 const std::string &formspecPrepend,
98 bool remap_dbl_click):
99 GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
103 m_formspec_prepend(formspecPrepend),
106 m_joystick(joystick),
107 m_remap_dbl_click(remap_dbl_click)
109 current_keys_pending.key_down = false;
110 current_keys_pending.key_up = false;
111 current_keys_pending.key_enter = false;
112 current_keys_pending.key_escape = false;
114 m_doubleclickdetect[0].time = 0;
115 m_doubleclickdetect[1].time = 0;
117 m_doubleclickdetect[0].pos = v2s32(0, 0);
118 m_doubleclickdetect[1].pos = v2s32(0, 0);
120 m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
121 m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
124 GUIFormSpecMenu::~GUIFormSpecMenu()
128 for (auto &table_it : m_tables)
129 table_it.second->drop();
130 for (auto &inventorylist_it : m_inventorylists)
131 inventorylist_it.e->drop();
132 for (auto &checkbox_it : m_checkboxes)
133 checkbox_it.second->drop();
134 for (auto &scrollbar_it : m_scrollbars)
135 scrollbar_it.second->drop();
136 for (auto &background_it : m_backgrounds)
137 background_it->drop();
138 for (auto &tooltip_rect_it : m_tooltip_rects)
139 tooltip_rect_it.first->drop();
141 delete m_selected_item;
146 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
147 JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
148 const std::string &formspecPrepend)
150 if (cur_formspec == nullptr) {
151 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
152 client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
153 cur_formspec->doPause = false;
156 Caution: do not call (*cur_formspec)->drop() here --
157 the reference might outlive the menu, so we will
158 periodically check if *cur_formspec is the only
159 remaining reference (i.e. the menu was removed)
160 and delete it in that case.
164 cur_formspec->setFormspecPrepend(formspecPrepend);
165 cur_formspec->setFormSource(fs_src);
166 cur_formspec->setTextDest(txt_dest);
170 void GUIFormSpecMenu::removeChildren()
172 const core::list<gui::IGUIElement*> &children = getChildren();
174 while (!children.empty()) {
175 (*children.getLast())->remove();
178 if (m_tooltip_element) {
179 m_tooltip_element->remove();
180 m_tooltip_element->drop();
181 m_tooltip_element = nullptr;
185 void GUIFormSpecMenu::setInitialFocus()
187 // Set initial focus according to following order of precedence:
188 // 1. first empty editbox
192 // 5. first focusable (not statictext, not tabheader)
193 // 6. first child element
195 core::list<gui::IGUIElement*> children = getChildren();
197 // in case "children" contains any NULL elements, remove them
198 for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
199 it != children.end();) {
203 it = children.erase(it);
206 // 1. first empty editbox
207 for (gui::IGUIElement *it : children) {
208 if (it->getType() == gui::EGUIET_EDIT_BOX
209 && it->getText()[0] == 0) {
210 Environment->setFocus(it);
216 for (gui::IGUIElement *it : children) {
217 if (it->getType() == gui::EGUIET_EDIT_BOX) {
218 Environment->setFocus(it);
224 for (gui::IGUIElement *it : children) {
225 if (it->getTypeName() == std::string("GUITable")) {
226 Environment->setFocus(it);
232 for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
233 it != children.end(); --it) {
234 if ((*it)->getType() == gui::EGUIET_BUTTON) {
235 Environment->setFocus(*it);
240 // 5. first focusable (not statictext, not tabheader)
241 for (gui::IGUIElement *it : children) {
242 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
243 it->getType() != gui::EGUIET_TAB_CONTROL) {
244 Environment->setFocus(it);
249 // 6. first child element
250 if (children.empty())
251 Environment->setFocus(this);
253 Environment->setFocus(*(children.begin()));
256 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
258 for (auto &table : m_tables) {
259 if (tablename == table.first.fname)
265 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
267 for (auto &dropdown : m_dropdowns) {
268 if (name == dropdown.first.fname)
269 return &dropdown.second;
274 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
276 v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
278 pos_f.X += stof((*v_pos)[0]) * spacing.X;
279 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
281 return v2s32(pos_f.X, pos_f.Y);
284 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
286 return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
287 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
290 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
292 return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
295 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
297 std::vector<std::string> parts = split(element,',');
299 if (((parts.size() == 2) || parts.size() == 3) ||
300 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
302 if (parts[1].find(';') != std::string::npos)
303 parts[1] = parts[1].substr(0,parts[1].find(';'));
305 data->invsize.X = MYMAX(0, stof(parts[0]));
306 data->invsize.Y = MYMAX(0, stof(parts[1]));
310 if (parts.size() == 3) {
311 if (parts[2] == "true") {
312 lockSize(true,v2u32(800,600));
316 data->explicit_size = true;
319 errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl;
322 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
324 std::vector<std::string> parts = split(element, ',');
326 if (parts.size() >= 2) {
327 if (parts[1].find(';') != std::string::npos)
328 parts[1] = parts[1].substr(0, parts[1].find(';'));
330 container_stack.push(pos_offset);
331 pos_offset.X += stof(parts[0]);
332 pos_offset.Y += stof(parts[1]);
335 errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl;
338 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
340 if (container_stack.empty()) {
341 errorstream<< "Invalid container end element, no matching container start element" << std::endl;
343 pos_offset = container_stack.top();
344 container_stack.pop();
348 void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
351 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
355 std::vector<std::string> parts = split(element,';');
357 if (((parts.size() == 4) || (parts.size() == 5)) ||
358 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
360 std::string location = parts[0];
361 std::string listname = parts[1];
362 std::vector<std::string> v_pos = split(parts[2],',');
363 std::vector<std::string> v_geom = split(parts[3],',');
364 std::string startindex;
365 if (parts.size() == 5)
366 startindex = parts[4];
368 MY_CHECKPOS("list",2);
369 MY_CHECKGEOM("list",3);
371 InventoryLocation loc;
373 if (location == "context" || location == "current_name")
374 loc = m_current_inventory_location;
376 loc.deSerialize(location);
379 geom.X = stoi(v_geom[0]);
380 geom.Y = stoi(v_geom[1]);
383 if (!startindex.empty())
384 start_i = stoi(startindex);
386 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
387 errorstream<< "Invalid list element: '" << element << "'" << std::endl;
391 // check for the existence of inventory and list
392 Inventory *inv = m_invmgr->getInventory(loc);
394 warningstream << "GUIFormSpecMenu::parseList(): "
395 << "The inventory location "
396 << "\"" << loc.dump() << "\" doesn't exist"
400 InventoryList *ilist = inv->getList(listname);
402 warningstream << "GUIFormSpecMenu::parseList(): "
403 << "The inventory list \"" << listname << "\" "
404 << "@ \"" << loc.dump() << "\" doesn't exist"
409 // trim geom if it is larger than the actual inventory size
410 s32 list_size = (s32)ilist->getSize();
411 if (list_size < geom.X * geom.Y + start_i) {
412 list_size -= MYMAX(start_i, 0);
413 geom.Y = list_size / geom.X;
414 geom.Y += list_size % geom.X > 0 ? 1 : 0;
419 if (!data->explicit_size)
420 warningstream << "invalid use of list without a size[] element" << std::endl;
426 258 + m_fields.size(),
431 core::rect<s32> rect;
433 if (data->real_coordinates) {
434 pos = getRealCoordinateBasePos(v_pos);
435 rect = core::rect<s32>(pos.X, pos.Y,
436 pos.X + (geom.X - 1) * (imgsize.X * 1.25) + imgsize.X,
437 pos.Y + (geom.Y - 1) * (imgsize.Y * 1.25) + imgsize.Y);
439 pos = getElementBasePos(&v_pos);
440 rect = core::rect<s32>(pos.X, pos.Y,
441 pos.X + (geom.X - 1) * spacing.X + imgsize.X,
442 pos.Y + (geom.Y - 1) * spacing.Y + imgsize.Y);
445 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
446 this, spec.fid, rect);
448 m_inventorylists.emplace_back(loc, listname, e, geom, start_i,
449 data->real_coordinates);
450 m_fields.push_back(spec);
453 errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl;
456 void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element)
459 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
463 std::vector<std::string> parts = split(element, ';');
465 if (parts.size() == 2) {
466 std::string location = parts[0];
467 std::string listname = parts[1];
469 InventoryLocation loc;
471 if (location == "context" || location == "current_name")
472 loc = m_current_inventory_location;
474 loc.deSerialize(location);
476 m_inventory_rings.emplace_back(loc, listname);
480 if (element.empty() && m_inventorylists.size() > 1) {
481 size_t siz = m_inventorylists.size();
482 // insert the last two inv list elements into the list ring
483 const ListDrawSpec &spa = m_inventorylists[siz - 2];
484 const ListDrawSpec &spb = m_inventorylists[siz - 1];
485 m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname);
486 m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname);
490 errorstream<< "Invalid list ring element(" << parts.size() << ", "
491 << m_inventorylists.size() << "): '" << element << "'" << std::endl;
494 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
496 std::vector<std::string> parts = split(element,';');
498 if (((parts.size() >= 3) && (parts.size() <= 4)) ||
499 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
501 std::vector<std::string> v_pos = split(parts[0],',');
502 std::string name = parts[1];
503 std::string label = parts[2];
504 std::string selected;
506 if (parts.size() >= 4)
509 MY_CHECKPOS("checkbox",0);
511 bool fselected = false;
513 if (selected == "true")
516 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
517 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
518 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
519 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
522 core::rect<s32> rect;
524 if (data->real_coordinates) {
525 pos = getRealCoordinateBasePos(v_pos);
527 rect = core::rect<s32>(
530 pos.X + label_size.Width + cb_size + 7,
534 pos = getElementBasePos(&v_pos);
535 rect = core::rect<s32>(
537 pos.Y + imgsize.Y / 2 - y_center,
538 pos.X + label_size.Width + cb_size + 7,
539 pos.Y + imgsize.Y / 2 + y_center
545 wlabel, //Needed for displaying text on MSVC
550 spec.ftype = f_CheckBox;
552 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect, this,
553 spec.fid, spec.flabel.c_str());
555 auto style = getStyleForElement("checkbox", name);
556 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
558 if (spec.fname == data->focused_fieldname) {
559 Environment->setFocus(e);
563 m_checkboxes.emplace_back(spec, e);
564 m_fields.push_back(spec);
567 errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl;
570 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
572 std::vector<std::string> parts = split(element,';');
574 if (parts.size() >= 5) {
575 std::vector<std::string> v_pos = split(parts[0],',');
576 std::vector<std::string> v_geom = split(parts[1],',');
577 std::string name = parts[3];
578 std::string value = parts[4];
580 MY_CHECKPOS("scrollbar",0);
581 MY_CHECKGEOM("scrollbar",1);
586 if (data->real_coordinates) {
587 pos = getRealCoordinateBasePos(v_pos);
588 dim = getRealCoordinateGeometry(v_geom);
590 pos = getElementBasePos(&v_pos);
591 dim.X = stof(v_geom[0]) * spacing.X;
592 dim.Y = stof(v_geom[1]) * spacing.Y;
595 core::rect<s32> rect =
596 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
605 bool is_horizontal = true;
607 if (parts[2] == "vertical")
608 is_horizontal = false;
610 spec.ftype = f_ScrollBar;
612 GUIScrollBar *e = new GUIScrollBar(Environment, this, spec.fid, rect,
613 is_horizontal, true);
615 auto style = getStyleForElement("scrollbar", name);
616 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
617 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
619 s32 max = data->scrollbar_options.max;
620 s32 min = data->scrollbar_options.min;
625 e->setPos(stoi(parts[4]));
627 e->setSmallStep(data->scrollbar_options.small_step);
628 e->setLargeStep(data->scrollbar_options.large_step);
630 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
632 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
634 m_scrollbars.emplace_back(spec,e);
635 m_fields.push_back(spec);
638 errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element
642 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
644 std::vector<std::string> parts = split(element, ';');
646 if (parts.size() == 0) {
647 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
648 element << "'" << std::endl;
652 for (const std::string &i : parts) {
653 std::vector<std::string> options = split(i, '=');
655 if (options.size() != 2) {
656 warningstream << "Invalid scrollbaroptions option syntax: '" <<
657 element << "'" << std::endl;
658 continue; // Go to next option
661 if (options[0] == "max") {
662 data->scrollbar_options.max = stoi(options[1]);
664 } else if (options[0] == "min") {
665 data->scrollbar_options.min = stoi(options[1]);
667 } else if (options[0] == "smallstep") {
668 int value = stoi(options[1]);
669 data->scrollbar_options.small_step = value < 0 ? 10 : value;
671 } else if (options[0] == "largestep") {
672 int value = stoi(options[1]);
673 data->scrollbar_options.large_step = value < 0 ? 100 : value;
675 } else if (options[0] == "thumbsize") {
676 int value = stoi(options[1]);
677 data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
679 } else if (options[0] == "arrows") {
680 std::string value = trim(options[1]);
682 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
683 else if (value == "show")
684 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
685 else // Auto hide/show
686 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
690 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
691 "): '" << element << "'" << std::endl;
695 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
697 std::vector<std::string> parts = split(element,';');
699 if ((parts.size() == 3) ||
700 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
702 std::vector<std::string> v_pos = split(parts[0],',');
703 std::vector<std::string> v_geom = split(parts[1],',');
704 std::string name = unescape_string(parts[2]);
706 MY_CHECKPOS("image", 0);
707 MY_CHECKGEOM("image", 1);
712 if (data->real_coordinates) {
713 pos = getRealCoordinateBasePos(v_pos);
714 geom = getRealCoordinateGeometry(v_geom);
716 pos = getElementBasePos(&v_pos);
717 geom.X = stof(v_geom[0]) * (float)imgsize.X;
718 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
721 if (!data->explicit_size)
722 warningstream<<"invalid use of image without a size[] element"<<std::endl;
724 video::ITexture *texture = m_tsrc->getTexture(name);
726 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
727 << std::endl << "\t" << name << std::endl;
735 258 + m_fields.size(),
738 core::rect<s32> rect(pos, pos + geom);
739 gui::IGUIImage *e = Environment->addImage(rect, this, spec.fid, 0, true);
740 e->setImage(texture);
741 e->setScaleImage(true);
742 e->setNotClipped(true);
743 m_fields.push_back(spec);
748 if (parts.size() == 2) {
749 std::vector<std::string> v_pos = split(parts[0],',');
750 std::string name = unescape_string(parts[1]);
752 MY_CHECKPOS("image", 0);
754 v2s32 pos = getElementBasePos(&v_pos);
756 if (!data->explicit_size)
757 warningstream<<"invalid use of image without a size[] element"<<std::endl;
759 video::ITexture *texture = m_tsrc->getTexture(name);
761 errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
762 << std::endl << "\t" << name << std::endl;
770 258 + m_fields.size()
772 gui::IGUIImage *e = Environment->addImage(texture, pos, true, this,
774 e->setNotClipped(true);
775 m_fields.push_back(spec);
779 errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl;
782 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
784 std::vector<std::string> parts = split(element,';');
786 if ((parts.size() == 3) ||
787 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
789 std::vector<std::string> v_pos = split(parts[0],',');
790 std::vector<std::string> v_geom = split(parts[1],',');
791 std::string name = parts[2];
793 MY_CHECKPOS("itemimage",0);
794 MY_CHECKGEOM("itemimage",1);
799 if (data->real_coordinates) {
800 pos = getRealCoordinateBasePos(v_pos);
801 geom = getRealCoordinateGeometry(v_geom);
803 pos = getElementBasePos(&v_pos);
804 geom.X = stof(v_geom[0]) * (float)imgsize.X;
805 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
808 if(!data->explicit_size)
809 warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
815 258 + m_fields.size(),
818 spec.ftype = f_ItemImage;
820 GUIItemImage *e = new GUIItemImage(Environment, this, spec.fid,
821 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
824 m_fields.push_back(spec);
827 errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
830 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
831 const std::string &type)
833 std::vector<std::string> parts = split(element,';');
835 if ((parts.size() == 4) ||
836 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
838 std::vector<std::string> v_pos = split(parts[0],',');
839 std::vector<std::string> v_geom = split(parts[1],',');
840 std::string name = parts[2];
841 std::string label = parts[3];
843 MY_CHECKPOS("button",0);
844 MY_CHECKGEOM("button",1);
848 core::rect<s32> rect;
850 if (data->real_coordinates) {
851 pos = getRealCoordinateBasePos(v_pos);
852 geom = getRealCoordinateGeometry(v_geom);
853 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
856 pos = getElementBasePos(&v_pos);
857 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
858 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
860 rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
861 pos.X + geom.X, pos.Y + m_btn_height);
864 if(!data->explicit_size)
865 warningstream<<"invalid use of button without a size[] element"<<std::endl;
867 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
873 258 + m_fields.size()
875 spec.ftype = f_Button;
876 if(type == "button_exit")
879 GUIButton *e = GUIButton::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
881 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
882 if (style.isNotDefault(StyleSpec::BGCOLOR)) {
883 e->setColor(style.getColor(StyleSpec::BGCOLOR));
885 if (style.isNotDefault(StyleSpec::BGCOLOR_HOVERED)) {
886 e->setHoveredColor(style.getColor(StyleSpec::BGCOLOR_HOVERED));
888 if (style.isNotDefault(StyleSpec::BGCOLOR_PRESSED)) {
889 e->setPressedColor(style.getColor(StyleSpec::BGCOLOR_PRESSED));
892 if (style.isNotDefault(StyleSpec::TEXTCOLOR)) {
893 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR));
895 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
896 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
898 if (style.isNotDefault(StyleSpec::BGIMG)) {
899 std::string image_name = style.get(StyleSpec::BGIMG, "");
900 std::string hovered_image_name = style.get(StyleSpec::BGIMG_HOVERED, "");
901 std::string pressed_image_name = style.get(StyleSpec::BGIMG_PRESSED, "");
903 video::ITexture *texture = 0;
904 video::ITexture *hovered_texture = 0;
905 video::ITexture *pressed_texture = 0;
906 texture = m_tsrc->getTexture(image_name);
907 if (!hovered_image_name.empty())
908 hovered_texture = m_tsrc->getTexture(hovered_image_name);
910 hovered_texture = texture;
911 if (!pressed_image_name.empty())
912 pressed_texture = m_tsrc->getTexture(pressed_image_name);
914 pressed_texture = texture;
916 e->setUseAlphaChannel(style.getBool(StyleSpec::ALPHA, true));
917 e->setImage(guiScalingImageButton(
918 Environment->getVideoDriver(), texture, geom.X, geom.Y));
919 e->setHoveredImage(guiScalingImageButton(
920 Environment->getVideoDriver(), hovered_texture, geom.X, geom.Y));
921 e->setPressedImage(guiScalingImageButton(
922 Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
923 e->setScaleImage(true);
926 if (spec.fname == data->focused_fieldname) {
927 Environment->setFocus(e);
930 m_fields.push_back(spec);
933 errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl;
936 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
938 std::vector<std::string> parts = split(element,';');
940 if ((parts.size() >= 3 && parts.size() <= 5) ||
941 (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
942 std::vector<std::string> v_pos = split(parts[0],',');
943 std::vector<std::string> v_geom = split(parts[1],',');
944 std::string name = unescape_string(parts[2]);
946 MY_CHECKPOS("background",0);
947 MY_CHECKGEOM("background",1);
952 if (data->real_coordinates) {
953 pos = getRealCoordinateBasePos(v_pos);
954 geom = getRealCoordinateGeometry(v_geom);
956 pos = getElementBasePos(&v_pos);
957 pos.X -= (spacing.X - (float)imgsize.X) / 2;
958 pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
960 geom.X = stof(v_geom[0]) * spacing.X;
961 geom.Y = stof(v_geom[1]) * spacing.Y;
965 if (parts.size() >= 4 && is_yes(parts[3])) {
966 if (data->real_coordinates) {
967 pos = getRealCoordinateBasePos(v_pos) * -1;
970 pos.X = stoi(v_pos[0]); //acts as offset
971 pos.Y = stoi(v_pos[1]);
976 core::rect<s32> middle;
977 if (parts.size() >= 5) {
978 std::vector<std::string> v_middle = split(parts[4], ',');
979 if (v_middle.size() == 1) {
980 s32 x = stoi(v_middle[0]);
981 middle.UpperLeftCorner = core::vector2di(x, x);
982 middle.LowerRightCorner = core::vector2di(-x, -x);
983 } else if (v_middle.size() == 2) {
984 s32 x = stoi(v_middle[0]);
985 s32 y = stoi(v_middle[1]);
986 middle.UpperLeftCorner = core::vector2di(x, y);
987 middle.LowerRightCorner = core::vector2di(-x, -y);
988 // `-x` is interpreted as `w - x`
989 } else if (v_middle.size() == 4) {
990 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
991 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
993 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
997 if (!data->explicit_size && !clip)
998 warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1004 258 + m_fields.size()
1007 core::rect<s32> rect;
1009 // no auto_clip => position like normal image
1010 rect = core::rect<s32>(pos, pos + geom);
1012 // it will be auto-clipped when drawing
1013 rect = core::rect<s32>(-pos, pos);
1016 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1017 rect, name, middle, m_tsrc, clip);
1019 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1021 e->setNotClipped(true);
1023 e->setVisible(false); // the element is drawn manually before all others
1025 m_backgrounds.push_back(e);
1026 m_fields.push_back(spec);
1029 errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl;
1032 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1034 std::vector<std::string> parts = split(element,';');
1036 data->table_options.clear();
1037 for (const std::string &part : parts) {
1038 // Parse table option
1039 std::string opt = unescape_string(part);
1040 data->table_options.push_back(GUITable::splitOption(opt));
1044 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1046 std::vector<std::string> parts = split(element,';');
1048 data->table_columns.clear();
1049 for (const std::string &part : parts) {
1050 std::vector<std::string> col_parts = split(part,',');
1051 GUITable::TableColumn column;
1052 // Parse column type
1053 if (!col_parts.empty())
1054 column.type = col_parts[0];
1055 // Parse column options
1056 for (size_t j = 1; j < col_parts.size(); ++j) {
1057 std::string opt = unescape_string(col_parts[j]);
1058 column.options.push_back(GUITable::splitOption(opt));
1060 data->table_columns.push_back(column);
1064 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1066 std::vector<std::string> parts = split(element,';');
1068 if (((parts.size() == 4) || (parts.size() == 5)) ||
1069 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1071 std::vector<std::string> v_pos = split(parts[0],',');
1072 std::vector<std::string> v_geom = split(parts[1],',');
1073 std::string name = parts[2];
1074 std::vector<std::string> items = split(parts[3],',');
1075 std::string str_initial_selection;
1076 std::string str_transparent = "false";
1078 if (parts.size() >= 5)
1079 str_initial_selection = parts[4];
1081 MY_CHECKPOS("table",0);
1082 MY_CHECKGEOM("table",1);
1087 if (data->real_coordinates) {
1088 pos = getRealCoordinateBasePos(v_pos);
1089 geom = getRealCoordinateGeometry(v_geom);
1091 pos = getElementBasePos(&v_pos);
1092 geom.X = stof(v_geom[0]) * spacing.X;
1093 geom.Y = stof(v_geom[1]) * spacing.Y;
1096 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1102 258 + m_fields.size()
1105 spec.ftype = f_Table;
1107 for (std::string &item : items) {
1108 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1111 //now really show table
1112 GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc);
1114 if (spec.fname == data->focused_fieldname) {
1115 Environment->setFocus(e);
1118 e->setTable(data->table_options, data->table_columns, items);
1120 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1121 e->setDynamicData(data->table_dyndata[name]);
1124 if (!str_initial_selection.empty() && str_initial_selection != "0")
1125 e->setSelected(stoi(str_initial_selection));
1127 auto style = getStyleForElement("table", name);
1128 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1130 m_tables.emplace_back(spec, e);
1131 m_fields.push_back(spec);
1134 errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl;
1137 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1139 std::vector<std::string> parts = split(element,';');
1141 if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1142 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1144 std::vector<std::string> v_pos = split(parts[0],',');
1145 std::vector<std::string> v_geom = split(parts[1],',');
1146 std::string name = parts[2];
1147 std::vector<std::string> items = split(parts[3],',');
1148 std::string str_initial_selection;
1149 std::string str_transparent = "false";
1151 if (parts.size() >= 5)
1152 str_initial_selection = parts[4];
1154 if (parts.size() >= 6)
1155 str_transparent = parts[5];
1157 MY_CHECKPOS("textlist",0);
1158 MY_CHECKGEOM("textlist",1);
1163 if (data->real_coordinates) {
1164 pos = getRealCoordinateBasePos(v_pos);
1165 geom = getRealCoordinateGeometry(v_geom);
1167 pos = getElementBasePos(&v_pos);
1168 geom.X = stof(v_geom[0]) * spacing.X;
1169 geom.Y = stof(v_geom[1]) * spacing.Y;
1172 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1178 258 + m_fields.size()
1181 spec.ftype = f_Table;
1183 for (std::string &item : items) {
1184 item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1187 //now really show list
1188 GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc);
1190 if (spec.fname == data->focused_fieldname) {
1191 Environment->setFocus(e);
1194 e->setTextList(items, is_yes(str_transparent));
1196 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1197 e->setDynamicData(data->table_dyndata[name]);
1200 if (!str_initial_selection.empty() && str_initial_selection != "0")
1201 e->setSelected(stoi(str_initial_selection));
1203 auto style = getStyleForElement("textlist", name);
1204 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1206 m_tables.emplace_back(spec, e);
1207 m_fields.push_back(spec);
1210 errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl;
1214 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1216 std::vector<std::string> parts = split(element,';');
1218 if ((parts.size() == 5) ||
1219 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1221 std::vector<std::string> v_pos = split(parts[0],',');
1222 std::string name = parts[2];
1223 std::vector<std::string> items = split(parts[3],',');
1224 std::string str_initial_selection;
1225 str_initial_selection = parts[4];
1227 MY_CHECKPOS("dropdown",0);
1231 core::rect<s32> rect;
1233 if (data->real_coordinates) {
1234 std::vector<std::string> v_geom = split(parts[1],',');
1236 if (v_geom.size() == 1)
1237 v_geom.emplace_back("1");
1239 MY_CHECKGEOM("dropdown",1);
1241 pos = getRealCoordinateBasePos(v_pos);
1242 geom = getRealCoordinateGeometry(v_geom);
1243 rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1245 pos = getElementBasePos(&v_pos);
1247 s32 width = stof(parts[1]) * spacing.Y;
1249 rect = core::rect<s32>(pos.X, pos.Y,
1250 pos.X + width, pos.Y + (m_btn_height * 2));
1257 258 + m_fields.size()
1260 spec.ftype = f_DropDown;
1263 //now really show list
1264 gui::IGUIComboBox *e = Environment->addComboBox(rect, this, spec.fid);
1266 if (spec.fname == data->focused_fieldname) {
1267 Environment->setFocus(e);
1270 for (const std::string &item : items) {
1271 e->addItem(unescape_translate(unescape_string(
1272 utf8_to_wide(item))).c_str());
1275 if (!str_initial_selection.empty())
1276 e->setSelected(stoi(str_initial_selection)-1);
1278 auto style = getStyleForElement("dropdown", name);
1279 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1281 m_fields.push_back(spec);
1283 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1284 std::vector<std::string> &values = m_dropdowns.back().second;
1285 for (const std::string &item : items) {
1286 values.push_back(unescape_string(item));
1291 errorstream << "Invalid dropdown element(" << parts.size() << "): '"
1292 << element << "'" << std::endl;
1295 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1297 std::vector<std::string> parts = split(element,';');
1298 if (parts.size() == 2 ||
1299 (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1300 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1304 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1306 std::vector<std::string> parts = split(element,';');
1308 if ((parts.size() == 4) || (parts.size() == 5) ||
1309 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1311 std::vector<std::string> v_pos = split(parts[0],',');
1312 std::vector<std::string> v_geom = split(parts[1],',');
1313 std::string name = parts[2];
1314 std::string label = parts[3];
1316 MY_CHECKPOS("pwdfield",0);
1317 MY_CHECKGEOM("pwdfield",1);
1322 if (data->real_coordinates) {
1323 pos = getRealCoordinateBasePos(v_pos);
1324 geom = getRealCoordinateGeometry(v_geom);
1326 pos = getElementBasePos(&v_pos);
1329 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1331 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1332 pos.Y -= m_btn_height;
1333 geom.Y = m_btn_height*2;
1336 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1338 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1344 258 + m_fields.size()
1348 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
1350 if (spec.fname == data->focused_fieldname) {
1351 Environment->setFocus(e);
1354 if (label.length() >= 1) {
1355 int font_height = g_fontengine->getTextHeight();
1356 rect.UpperLeftCorner.Y -= font_height;
1357 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1358 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1362 e->setPasswordBox(true,L'*');
1364 auto style = getStyleForElement("pwdfield", name, "field");
1365 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1366 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1367 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1370 evt.EventType = EET_KEY_INPUT_EVENT;
1371 evt.KeyInput.Key = KEY_END;
1372 evt.KeyInput.Char = 0;
1373 evt.KeyInput.Control = false;
1374 evt.KeyInput.Shift = false;
1375 evt.KeyInput.PressedDown = true;
1378 if (parts.size() >= 5) {
1379 // TODO: remove after 2016-11-03
1380 warningstream << "pwdfield: use field_close_on_enter[name, enabled]" <<
1381 " instead of the 5th param" << std::endl;
1382 field_close_on_enter[name] = is_yes(parts[4]);
1385 m_fields.push_back(spec);
1388 errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl;
1391 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1392 core::rect<s32> &rect, bool is_multiline)
1394 bool is_editable = !spec.fname.empty();
1395 if (!is_editable && !is_multiline) {
1396 // spec field id to 0, this stops submit searching for a value that isn't there
1397 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1404 } else if (is_multiline &&
1405 spec.fdefault.empty() && !spec.flabel.empty()) {
1406 // Multiline textareas: swap default and label for backwards compat
1407 spec.flabel.swap(spec.fdefault);
1410 gui::IGUIEditBox *e = nullptr;
1411 static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1412 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1414 if (use_intl_edit_box && g_settings->getBool("freetype")) {
1415 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1416 this, spec.fid, rect, is_editable, is_multiline);
1419 e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true,
1420 Environment, this, spec.fid, rect, is_editable, true);
1421 } else if (is_editable) {
1422 e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this,
1428 auto style = getStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1431 if (is_editable && spec.fname == data->focused_fieldname)
1432 Environment->setFocus(e);
1435 e->setMultiLine(true);
1436 e->setWordWrap(true);
1437 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1440 evt.EventType = EET_KEY_INPUT_EVENT;
1441 evt.KeyInput.Key = KEY_END;
1442 evt.KeyInput.Char = 0;
1443 evt.KeyInput.Control = 0;
1444 evt.KeyInput.Shift = 0;
1445 evt.KeyInput.PressedDown = true;
1449 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1450 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1451 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1452 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1453 e->setDrawBackground(false);
1459 if (!spec.flabel.empty()) {
1460 int font_height = g_fontengine->getTextHeight();
1461 rect.UpperLeftCorner.Y -= font_height;
1462 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1463 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1464 rect, false, true, this, 0);
1467 t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1471 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1472 std::vector<std::string> &parts)
1474 std::string name = parts[0];
1475 std::string label = parts[1];
1476 std::string default_val = parts[2];
1478 core::rect<s32> rect;
1480 if (data->explicit_size)
1481 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1483 v2s32 pos = getElementBasePos(nullptr);
1484 pos.Y = (data->simple_field_count + 2) * 60;
1485 v2s32 size = DesiredRect.getSize();
1487 rect = core::rect<s32>(
1488 size.X / 2 - 150, pos.Y,
1489 size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1494 default_val = m_form_src->resolveText(default_val);
1497 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1502 utf8_to_wide(unescape_string(default_val)),
1503 258 + m_fields.size()
1506 createTextField(data, spec, rect, false);
1508 m_fields.push_back(spec);
1510 data->simple_field_count++;
1513 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1514 const std::string &type)
1516 std::vector<std::string> v_pos = split(parts[0],',');
1517 std::vector<std::string> v_geom = split(parts[1],',');
1518 std::string name = parts[2];
1519 std::string label = parts[3];
1520 std::string default_val = parts[4];
1522 MY_CHECKPOS(type,0);
1523 MY_CHECKGEOM(type,1);
1528 if (data->real_coordinates) {
1529 pos = getRealCoordinateBasePos(v_pos);
1530 geom = getRealCoordinateGeometry(v_geom);
1532 pos = getElementBasePos(&v_pos);
1535 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1537 if (type == "textarea")
1539 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1540 pos.Y += m_btn_height;
1544 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1545 pos.Y -= m_btn_height;
1546 geom.Y = m_btn_height*2;
1550 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1552 if(!data->explicit_size)
1553 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1556 default_val = m_form_src->resolveText(default_val);
1559 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1564 utf8_to_wide(unescape_string(default_val)),
1565 258 + m_fields.size()
1568 createTextField(data, spec, rect, type == "textarea");
1570 if (parts.size() >= 6) {
1571 // TODO: remove after 2016-11-03
1572 warningstream << "field/textarea: use field_close_on_enter[name, enabled]" <<
1573 " instead of the 6th param" << std::endl;
1574 field_close_on_enter[name] = is_yes(parts[5]);
1577 m_fields.push_back(spec);
1580 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1581 const std::string &type)
1583 std::vector<std::string> parts = split(element,';');
1585 if (parts.size() == 3 || parts.size() == 4) {
1586 parseSimpleField(data,parts);
1590 if ((parts.size() == 5) || (parts.size() == 6) ||
1591 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1593 parseTextArea(data,parts,type);
1596 errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl;
1599 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1601 std::vector<std::string> parts = split(element, ';');
1603 if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1604 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl;
1608 std::vector<std::string> v_pos = split(parts[0], ',');
1609 std::vector<std::string> v_geom = split(parts[1], ',');
1610 std::string name = parts[2];
1611 std::string text = parts[3];
1613 MY_CHECKPOS("hypertext", 0);
1614 MY_CHECKGEOM("hypertext", 1);
1619 if (data->real_coordinates) {
1620 pos = getRealCoordinateBasePos(v_pos);
1621 geom = getRealCoordinateGeometry(v_geom);
1623 pos = getElementBasePos(&v_pos);
1626 pos.X += stof(v_pos[0]) * spacing.X;
1627 pos.Y += stof(v_pos[1]) * spacing.Y + (m_btn_height * 2);
1629 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1630 geom.Y = (stof(v_geom[1]) * imgsize.Y) - (spacing.Y - imgsize.Y);
1633 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1636 text = m_form_src->resolveText(text);
1640 utf8_to_wide(unescape_string(text)),
1642 258 + m_fields.size()
1645 spec.ftype = f_Unknown;
1647 spec.flabel.c_str(), Environment, this, spec.fid, rect, m_client, m_tsrc);
1649 m_fields.push_back(spec);
1652 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1654 std::vector<std::string> parts = split(element,';');
1656 if ((parts.size() == 2) ||
1657 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1659 std::vector<std::string> v_pos = split(parts[0],',');
1660 std::string text = parts[1];
1662 MY_CHECKPOS("label",0);
1664 if(!data->explicit_size)
1665 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1667 std::vector<std::string> lines = split(text, '\n');
1669 for (unsigned int i = 0; i != lines.size(); i++) {
1670 std::wstring wlabel_colors = translate_string(
1671 utf8_to_wide(unescape_string(lines[i])));
1672 // Without color escapes to get the font dimensions
1673 std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1675 core::rect<s32> rect;
1677 if (data->real_coordinates) {
1678 // Lines are spaced at the distance of 1/2 imgsize.
1679 // This alows lines that line up with the new elements
1680 // easily without sacrificing good line distance. If
1681 // it was one whole imgsize, it would have too much
1683 v2s32 pos = getRealCoordinateBasePos(v_pos);
1685 // Labels are positioned by their center, not their top.
1686 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1688 rect = core::rect<s32>(
1690 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1694 // Lines are spaced at the nominal distance of
1695 // 2/5 inventory slot, even if the font doesn't
1696 // quite match that. This provides consistent
1697 // form layout, at the expense of sometimes
1698 // having sub-optimal spacing for the font.
1699 // We multiply by 2 and then divide by 5, rather
1700 // than multiply by 0.4, to get exact results
1701 // in the integer cases: 0.4 is not exactly
1702 // representable in binary floating point.
1704 v2s32 pos = getElementBasePos(nullptr);
1705 pos.X += stof(v_pos[0]) * spacing.X;
1706 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1708 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1710 rect = core::rect<s32>(
1711 pos.X, pos.Y - m_btn_height,
1712 pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1713 pos.Y + m_btn_height);
1720 258 + m_fields.size(),
1723 gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1724 spec.flabel.c_str(), rect, false, false, this, spec.fid);
1725 e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1727 auto style = getStyleForElement("label", spec.fname);
1728 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1729 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1731 m_fields.push_back(spec);
1736 errorstream << "Invalid label element(" << parts.size() << "): '" << element
1737 << "'" << std::endl;
1740 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1742 std::vector<std::string> parts = split(element,';');
1744 if ((parts.size() == 2) ||
1745 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1747 std::vector<std::string> v_pos = split(parts[0],',');
1748 std::wstring text = unescape_translate(
1749 unescape_string(utf8_to_wide(parts[1])));
1751 MY_CHECKPOS("vertlabel",1);
1754 core::rect<s32> rect;
1756 if (data->real_coordinates) {
1757 pos = getRealCoordinateBasePos(v_pos);
1759 // Vertlabels are positioned by center, not left.
1760 pos.X -= imgsize.X / 2;
1762 // We use text.length + 1 because without it, the rect
1763 // isn't quite tall enough and cuts off the text.
1764 rect = core::rect<s32>(pos.X, pos.Y,
1766 pos.Y + font_line_height(m_font) *
1767 (text.length() + 1));
1770 pos = getElementBasePos(&v_pos);
1772 // As above, the length must be one longer. The width of
1773 // the rect (15 pixels) seems rather arbitrary, but
1774 // changing it might break something.
1775 rect = core::rect<s32>(
1776 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1778 font_line_height(m_font) *
1779 (text.length() + 1) +
1780 ((imgsize.Y/2) - m_btn_height));
1783 if(!data->explicit_size)
1784 warningstream<<"invalid use of label without a size[] element"<<std::endl;
1788 for (wchar_t i : text) {
1797 258 + m_fields.size()
1799 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1800 rect, false, false, this, spec.fid);
1801 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1803 auto style = getStyleForElement("vertlabel", spec.fname, "label");
1804 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1805 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1807 m_fields.push_back(spec);
1810 errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl;
1813 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1814 const std::string &type)
1816 std::vector<std::string> parts = split(element,';');
1818 if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1819 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1821 std::vector<std::string> v_pos = split(parts[0],',');
1822 std::vector<std::string> v_geom = split(parts[1],',');
1823 std::string image_name = parts[2];
1824 std::string name = parts[3];
1825 std::string label = parts[4];
1827 MY_CHECKPOS("imagebutton",0);
1828 MY_CHECKGEOM("imagebutton",1);
1830 bool noclip = false;
1831 bool drawborder = true;
1832 std::string pressed_image_name;
1834 if (parts.size() >= 7) {
1835 if (parts[5] == "true")
1837 if (parts[6] == "false")
1841 if (parts.size() >= 8) {
1842 pressed_image_name = parts[7];
1848 if (data->real_coordinates) {
1849 pos = getRealCoordinateBasePos(v_pos);
1850 geom = getRealCoordinateGeometry(v_geom);
1852 pos = getElementBasePos(&v_pos);
1853 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1854 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1857 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1860 if (!data->explicit_size)
1861 warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1863 image_name = unescape_string(image_name);
1864 pressed_image_name = unescape_string(pressed_image_name);
1866 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1871 utf8_to_wide(image_name),
1872 258 + m_fields.size()
1874 spec.ftype = f_Button;
1875 if (type == "image_button_exit")
1876 spec.is_exit = true;
1878 video::ITexture *texture = 0;
1879 video::ITexture *pressed_texture = 0;
1880 texture = m_tsrc->getTexture(image_name);
1881 if (!pressed_image_name.empty())
1882 pressed_texture = m_tsrc->getTexture(pressed_image_name);
1884 pressed_texture = texture;
1886 GUIButton *e = GUIButton::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
1888 if (spec.fname == data->focused_fieldname) {
1889 Environment->setFocus(e);
1892 auto style = getStyleForElement("image_button", spec.fname);
1894 e->setUseAlphaChannel(style.getBool(StyleSpec::ALPHA, true));
1895 e->setImage(guiScalingImageButton(
1896 Environment->getVideoDriver(), texture, geom.X, geom.Y));
1897 e->setPressedImage(guiScalingImageButton(
1898 Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
1899 e->setScaleImage(true);
1900 if (parts.size() >= 7) {
1901 e->setNotClipped(noclip);
1902 e->setDrawBorder(drawborder);
1904 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1905 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1908 m_fields.push_back(spec);
1912 errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
1915 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1917 std::vector<std::string> parts = split(element, ';');
1919 if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
1920 data->real_coordinates) || ((parts.size() > 6) &&
1921 (m_formspec_version > FORMSPEC_API_VERSION)))
1923 std::vector<std::string> v_pos = split(parts[0],',');
1925 // If we're using real coordinates, add an extra field for height.
1926 // Width is not here because tabs are the width of the text, and
1927 // there's no reason to change that.
1929 std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
1930 bool auto_width = true;
1931 if (parts.size() == 7) {
1934 v_geom = split(parts[1], ',');
1935 if (v_geom.size() == 1)
1936 v_geom.insert(v_geom.begin(), "1"); // Dummy value
1941 std::string name = parts[i+1];
1942 std::vector<std::string> buttons = split(parts[i+2], ',');
1943 std::string str_index = parts[i+3];
1944 bool show_background = true;
1945 bool show_border = true;
1946 int tab_index = stoi(str_index) - 1;
1948 MY_CHECKPOS("tabheader", 0);
1950 if (parts.size() == 6 + i) {
1951 if (parts[4+i] == "true")
1952 show_background = false;
1953 if (parts[5+i] == "false")
1954 show_border = false;
1961 258 + m_fields.size()
1964 spec.ftype = f_TabHeader;
1969 if (data->real_coordinates) {
1970 pos = getRealCoordinateBasePos(v_pos);
1972 geom = getRealCoordinateGeometry(v_geom);
1973 pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
1975 geom.X = DesiredRect.getWidth(); // Set automatic width
1977 MY_CHECKGEOM("tabheader", 1);
1979 v2f32 pos_f = pos_offset * spacing;
1980 pos_f.X += stof(v_pos[0]) * spacing.X;
1981 pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
1982 pos = v2s32(pos_f.X, pos_f.Y);
1984 geom.Y = m_btn_height * 2;
1985 geom.X = DesiredRect.getWidth();
1988 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1991 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1992 show_background, show_border, spec.fid);
1993 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1994 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1995 e->setTabHeight(geom.Y);
1997 if (spec.fname == data->focused_fieldname) {
1998 Environment->setFocus(e);
2001 auto style = getStyleForElement("tabheader", name);
2002 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2004 for (const std::string &button : buttons) {
2005 auto tab = e->addTab(unescape_translate(unescape_string(
2006 utf8_to_wide(button))).c_str(), -1);
2007 if (style.isNotDefault(StyleSpec::BGCOLOR))
2008 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2010 tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2013 if ((tab_index >= 0) &&
2014 (buttons.size() < INT_MAX) &&
2015 (tab_index < (int) buttons.size()))
2016 e->setActiveTab(tab_index);
2018 m_fields.push_back(spec);
2021 errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2022 << element << "'" << std::endl;
2025 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2028 if (m_client == 0) {
2029 warningstream << "invalid use of item_image_button with m_client==0"
2034 std::vector<std::string> parts = split(element,';');
2036 if ((parts.size() == 5) ||
2037 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2039 std::vector<std::string> v_pos = split(parts[0],',');
2040 std::vector<std::string> v_geom = split(parts[1],',');
2041 std::string item_name = parts[2];
2042 std::string name = parts[3];
2043 std::string label = parts[4];
2045 label = unescape_string(label);
2046 item_name = unescape_string(item_name);
2048 MY_CHECKPOS("itemimagebutton",0);
2049 MY_CHECKGEOM("itemimagebutton",1);
2054 if (data->real_coordinates) {
2055 pos = getRealCoordinateBasePos(v_pos);
2056 geom = getRealCoordinateGeometry(v_geom);
2058 pos = getElementBasePos(&v_pos);
2059 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2060 geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2063 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2065 if(!data->explicit_size)
2066 warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2068 IItemDefManager *idef = m_client->idef();
2070 item.deSerialize(item_name, idef);
2073 TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2074 m_default_tooltip_bgcolor,
2075 m_default_tooltip_color);
2077 // the spec for the button
2080 utf8_to_wide(label),
2081 utf8_to_wide(item_name),
2082 258 + m_fields.size(),
2086 gui::IGUIButton *e_btn = GUIButton::addButton(Environment, rect, this, spec_btn.fid, L"");
2088 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2089 e_btn->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
2090 e_btn->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
2092 if (spec_btn.fname == data->focused_fieldname) {
2093 Environment->setFocus(e_btn);
2096 spec_btn.ftype = f_Button;
2097 rect += data->basepos-padding;
2098 spec_btn.rect = rect;
2099 m_fields.push_back(spec_btn);
2101 // the spec for the item-image
2106 258 + m_fields.size(),
2110 GUIItemImage *e_img = new GUIItemImage(Environment, e_btn, spec_img.fid,
2111 core::rect<s32>(0, 0, geom.X, geom.Y), item_name, m_font, m_client);
2113 e_img->setText(utf8_to_wide(label).c_str());
2117 m_fields.push_back(spec_img);
2120 errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
2123 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2125 std::vector<std::string> parts = split(element,';');
2127 if ((parts.size() == 3) ||
2128 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2130 std::vector<std::string> v_pos = split(parts[0],',');
2131 std::vector<std::string> v_geom = split(parts[1],',');
2133 MY_CHECKPOS("box",0);
2134 MY_CHECKGEOM("box",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;
2145 geom.Y = stof(v_geom[1]) * spacing.Y;
2148 video::SColor tmp_color;
2150 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2155 258 + m_fields.size(),
2160 core::rect<s32> rect(pos, pos + geom);
2162 GUIBox *e = new GUIBox(Environment, this, spec.fid, rect, tmp_color);
2164 e->setNotClipped(true);
2168 m_fields.push_back(spec);
2171 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl;
2175 errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl;
2178 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2180 std::vector<std::string> parts = split(element,';');
2181 const u32 parameter_count = parts.size();
2183 if ((parameter_count > 2 && m_formspec_version < 3) ||
2184 (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2185 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2186 << element << "'" << std::endl;
2191 if (parameter_count >= 1 && parts[0] != "")
2192 parseColorString(parts[0], m_bgcolor, false);
2195 if (parameter_count >= 2) {
2196 if (parts[1] == "both") {
2197 m_bgnonfullscreen = true;
2198 m_bgfullscreen = true;
2199 } else if (parts[1] == "neither") {
2200 m_bgnonfullscreen = false;
2201 m_bgfullscreen = false;
2202 } else if (parts[1] != "" || m_formspec_version < 3) {
2203 m_bgfullscreen = is_yes(parts[1]);
2204 m_bgnonfullscreen = !m_bgfullscreen;
2209 if (parameter_count >= 3 && parts[2] != "")
2210 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2213 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2215 std::vector<std::string> parts = split(element,';');
2217 if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2218 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2220 parseColorString(parts[0], m_slotbg_n, false);
2221 parseColorString(parts[1], m_slotbg_h, false);
2223 if (parts.size() >= 3) {
2224 if (parseColorString(parts[2], m_slotbordercolor, false)) {
2225 m_slotborder = true;
2228 if (parts.size() == 5) {
2229 video::SColor tmp_color;
2231 if (parseColorString(parts[3], tmp_color, false))
2232 m_default_tooltip_bgcolor = tmp_color;
2233 if (parseColorString(parts[4], tmp_color, false))
2234 m_default_tooltip_color = tmp_color;
2238 errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl;
2241 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2243 std::vector<std::string> parts = split(element,';');
2244 if (parts.size() < 2) {
2245 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2246 << element << "'" << std::endl;
2250 // Get mode and check size
2251 bool rect_mode = parts[0].find(',') != std::string::npos;
2252 size_t base_size = rect_mode ? 3 : 2;
2253 if (parts.size() != base_size && parts.size() != base_size + 2) {
2254 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2255 << element << "'" << std::endl;
2260 video::SColor bgcolor = m_default_tooltip_bgcolor;
2261 video::SColor color = m_default_tooltip_color;
2262 if (parts.size() == base_size + 2 &&
2263 (!parseColorString(parts[base_size], bgcolor, false) ||
2264 !parseColorString(parts[base_size + 1], color, false))) {
2265 errorstream << "Invalid color in tooltip element(" << parts.size()
2266 << "): '" << element << "'" << std::endl;
2270 // Make tooltip spec
2271 std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2272 TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2276 std::vector<std::string> v_pos = split(parts[0], ',');
2277 std::vector<std::string> v_geom = split(parts[1], ',');
2279 MY_CHECKPOS("tooltip", 0);
2280 MY_CHECKGEOM("tooltip", 1);
2285 if (data->real_coordinates) {
2286 pos = getRealCoordinateBasePos(v_pos);
2287 geom = getRealCoordinateGeometry(v_geom);
2289 pos = getElementBasePos(&v_pos);
2290 geom.X = stof(v_geom[0]) * spacing.X;
2291 geom.Y = stof(v_geom[1]) * spacing.Y;
2294 FieldSpec fieldspec(
2298 258 + m_fields.size()
2301 core::rect<s32> rect(pos, pos + geom);
2303 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2304 this, fieldspec.fid, rect);
2306 m_fields.push_back(fieldspec);
2307 m_tooltip_rects.emplace_back(e, spec);
2310 m_tooltips[parts[0]] = spec;
2314 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2320 std::vector<std::string> parts = split(data,'[');
2322 if (parts.size() < 2) {
2326 if (parts[0] != "formspec_version") {
2330 if (is_number(parts[1])) {
2331 m_formspec_version = mystoi(parts[1]);
2338 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2340 if (element.empty())
2343 std::vector<std::string> parts = split(element,'[');
2345 if (parts.size() < 2)
2348 std::string type = trim(parts[0]);
2349 std::string description = trim(parts[1]);
2351 if (type != "size" && type != "invsize")
2354 if (type == "invsize")
2355 log_deprecated("Deprecated formspec element \"invsize\" is used");
2357 parseSize(data, description);
2362 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2364 if (element.empty())
2367 std::vector<std::string> parts = split(element, '[');
2369 if (parts.size() != 2)
2372 std::string type = trim(parts[0]);
2373 std::string description = trim(parts[1]);
2375 if (type != "position")
2378 parsePosition(data, description);
2383 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2385 std::vector<std::string> parts = split(element, ',');
2387 if (parts.size() == 2) {
2388 data->offset.X = stof(parts[0]);
2389 data->offset.Y = stof(parts[1]);
2393 errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2396 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2398 if (element.empty())
2401 std::vector<std::string> parts = split(element, '[');
2403 if (parts.size() != 2)
2406 std::string type = trim(parts[0]);
2407 std::string description = trim(parts[1]);
2409 if (type != "anchor")
2412 parseAnchor(data, description);
2417 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2419 std::vector<std::string> parts = split(element, ',');
2421 if (parts.size() == 2) {
2422 data->anchor.X = stof(parts[0]);
2423 data->anchor.Y = stof(parts[1]);
2427 errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2428 << "'" << std::endl;
2431 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2433 std::vector<std::string> parts = split(element, ';');
2435 if (parts.size() < 2) {
2436 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2437 << "'" << std::endl;
2441 std::string selector = trim(parts[0]);
2442 if (selector.empty()) {
2443 errorstream << "Invalid style element (Selector required): '" << element
2444 << "'" << std::endl;
2450 for (size_t i = 1; i < parts.size(); i++) {
2451 size_t equal_pos = parts[i].find('=');
2452 if (equal_pos == std::string::npos) {
2453 errorstream << "Invalid style element (Property missing value): '" << element
2454 << "'" << std::endl;
2458 std::string propname = trim(parts[i].substr(0, equal_pos));
2459 std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2461 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2463 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2464 if (prop == StyleSpec::NONE) {
2465 if (property_warned.find(propname) != property_warned.end()) {
2466 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2468 << "'" << std::endl;
2469 property_warned.insert(propname);
2474 spec.set(prop, value);
2478 theme_by_type[selector] |= spec;
2480 theme_by_name[selector] |= spec;
2486 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2489 if (element.empty())
2492 if (parseVersionDirect(element))
2495 std::vector<std::string> parts = split(element,'[');
2497 // ugly workaround to keep compatibility
2498 if (parts.size() > 2) {
2499 if (trim(parts[0]) == "image") {
2500 for (unsigned int i=2;i< parts.size(); i++) {
2501 parts[1] += "[" + parts[i];
2507 if (parts.size() < 2) {
2511 std::string type = trim(parts[0]);
2512 std::string description = trim(parts[1]);
2514 if (type == "container") {
2515 parseContainer(data, description);
2519 if (type == "container_end") {
2520 parseContainerEnd(data);
2524 if (type == "list") {
2525 parseList(data, description);
2529 if (type == "listring") {
2530 parseListRing(data, description);
2534 if (type == "checkbox") {
2535 parseCheckbox(data, description);
2539 if (type == "image") {
2540 parseImage(data, description);
2544 if (type == "item_image") {
2545 parseItemImage(data, description);
2549 if (type == "button" || type == "button_exit") {
2550 parseButton(data, description, type);
2554 if (type == "background" || type == "background9") {
2555 parseBackground(data, description);
2559 if (type == "tableoptions"){
2560 parseTableOptions(data,description);
2564 if (type == "tablecolumns"){
2565 parseTableColumns(data,description);
2569 if (type == "table"){
2570 parseTable(data,description);
2574 if (type == "textlist"){
2575 parseTextList(data,description);
2579 if (type == "dropdown"){
2580 parseDropDown(data,description);
2584 if (type == "field_close_on_enter") {
2585 parseFieldCloseOnEnter(data, description);
2589 if (type == "pwdfield") {
2590 parsePwdField(data,description);
2594 if ((type == "field") || (type == "textarea")){
2595 parseField(data,description,type);
2599 if (type == "hypertext") {
2600 parseHyperText(data,description);
2604 if (type == "label") {
2605 parseLabel(data,description);
2609 if (type == "vertlabel") {
2610 parseVertLabel(data,description);
2614 if (type == "item_image_button") {
2615 parseItemImageButton(data,description);
2619 if ((type == "image_button") || (type == "image_button_exit")) {
2620 parseImageButton(data,description,type);
2624 if (type == "tabheader") {
2625 parseTabHeader(data,description);
2629 if (type == "box") {
2630 parseBox(data,description);
2634 if (type == "bgcolor") {
2635 parseBackgroundColor(data,description);
2639 if (type == "listcolors") {
2640 parseListColors(data,description);
2644 if (type == "tooltip") {
2645 parseTooltip(data,description);
2649 if (type == "scrollbar") {
2650 parseScrollBar(data, description);
2654 if (type == "real_coordinates") {
2655 data->real_coordinates = is_yes(description);
2659 if (type == "style") {
2660 parseStyle(data, description, false);
2664 if (type == "style_type") {
2665 parseStyle(data, description, true);
2669 if (type == "scrollbaroptions") {
2670 parseScrollBarOptions(data, description);
2675 infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2679 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2681 /* useless to regenerate without a screensize */
2682 if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2689 for (auto &m_table : m_tables) {
2690 std::string tablename = m_table.first.fname;
2691 GUITable *table = m_table.second;
2692 mydata.table_dyndata[tablename] = table->getDynamicData();
2696 if (!m_focused_element.empty())
2697 mydata.focused_fieldname = m_focused_element;
2700 gui::IGUIElement *focused_element = Environment->getFocus();
2701 if (focused_element && focused_element->getParent() == this) {
2702 s32 focused_id = focused_element->getID();
2703 if (focused_id > 257) {
2704 for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2705 if (field.fid == focused_id) {
2706 mydata.focused_fieldname = field.fname;
2716 for (auto &table_it : m_tables)
2717 table_it.second->drop();
2718 for (auto &inventorylist_it : m_inventorylists)
2719 inventorylist_it.e->drop();
2720 for (auto &checkbox_it : m_checkboxes)
2721 checkbox_it.second->drop();
2722 for (auto &scrollbar_it : m_scrollbars)
2723 scrollbar_it.second->drop();
2724 for (auto &background_it : m_backgrounds)
2725 background_it->drop();
2726 for (auto &tooltip_rect_it : m_tooltip_rects)
2727 tooltip_rect_it.first->drop();
2729 mydata.size= v2s32(100,100);
2730 mydata.screensize = screensize;
2731 mydata.offset = v2f32(0.5f, 0.5f);
2732 mydata.anchor = v2f32(0.5f, 0.5f);
2733 mydata.simple_field_count = 0;
2735 // Base position of contents of form
2736 mydata.basepos = getBasePos();
2738 /* Convert m_init_draw_spec to m_inventorylists */
2740 m_inventorylists.clear();
2741 m_backgrounds.clear();
2743 m_checkboxes.clear();
2744 m_scrollbars.clear();
2747 m_tooltip_rects.clear();
2748 m_inventory_rings.clear();
2749 m_dropdowns.clear();
2750 theme_by_name.clear();
2751 theme_by_type.clear();
2753 m_bgnonfullscreen = true;
2754 m_bgfullscreen = false;
2756 m_formspec_version = 1;
2759 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2760 m_bgcolor = video::SColor(
2761 (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2762 clamp_u8(myround(formspec_bgcolor.X)),
2763 clamp_u8(myround(formspec_bgcolor.Y)),
2764 clamp_u8(myround(formspec_bgcolor.Z))
2769 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2770 m_fullscreen_bgcolor = video::SColor(
2771 (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2772 clamp_u8(myround(formspec_bgcolor.X)),
2773 clamp_u8(myround(formspec_bgcolor.Y)),
2774 clamp_u8(myround(formspec_bgcolor.Z))
2778 m_slotbg_n = video::SColor(255,128,128,128);
2779 m_slotbg_h = video::SColor(255,192,192,192);
2781 m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2782 m_default_tooltip_color = video::SColor(255,255,255,255);
2784 m_slotbordercolor = video::SColor(200,0,0,0);
2785 m_slotborder = false;
2789 assert(!m_tooltip_element);
2790 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2791 m_tooltip_element = gui::StaticText::add(Environment, L"",
2792 core::rect<s32>(0, 0, 110, 18));
2793 m_tooltip_element->enableOverrideColor(true);
2794 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2795 m_tooltip_element->setDrawBackground(true);
2796 m_tooltip_element->setDrawBorder(true);
2797 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2798 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2799 m_tooltip_element->setWordWrap(false);
2800 //we're not parent so no autograb for this one!
2801 m_tooltip_element->grab();
2804 std::vector<std::string> elements = split(m_formspec_string,']');
2807 /* try to read version from first element only */
2808 if (!elements.empty()) {
2809 if (parseVersionDirect(elements[0])) {
2814 /* we need size first in order to calculate image scale */
2815 mydata.explicit_size = false;
2816 for (; i< elements.size(); i++) {
2817 if (!parseSizeDirect(&mydata, elements[i])) {
2822 /* "position" element is always after "size" element if it used */
2823 for (; i< elements.size(); i++) {
2824 if (!parsePositionDirect(&mydata, elements[i])) {
2829 /* "anchor" element is always after "position" (or "size" element) if it used */
2830 for (; i< elements.size(); i++) {
2831 if (!parseAnchorDirect(&mydata, elements[i])) {
2836 /* "no_prepend" element is always after "position" (or "size" element) if it used */
2837 bool enable_prepends = true;
2838 for (; i < elements.size(); i++) {
2839 if (elements[i].empty())
2842 std::vector<std::string> parts = split(elements[i], '[');
2843 if (trim(parts[0]) == "no_prepend")
2844 enable_prepends = false;
2849 /* Copy of the "real_coordinates" element for after the form size. */
2850 mydata.real_coordinates = m_formspec_version >= 2;
2851 for (; i < elements.size(); i++) {
2852 std::vector<std::string> parts = split(elements[i], '[');
2853 std::string name = trim(parts[0]);
2854 if (name != "real_coordinates" || parts.size() != 2)
2855 break; // Invalid format
2857 mydata.real_coordinates = is_yes(trim(parts[1]));
2860 if (mydata.explicit_size) {
2861 // compute scaling for specified form size
2863 v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2864 v2u32 delta = current_screensize - m_lockscreensize;
2866 if (current_screensize.Y > m_lockscreensize.Y)
2871 if (current_screensize.X > m_lockscreensize.X)
2876 offset = v2s32(delta.X,delta.Y);
2878 mydata.screensize = m_lockscreensize;
2880 offset = v2s32(0,0);
2883 double gui_scaling = g_settings->getFloat("gui_scaling");
2884 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2888 // In fixed-size mode, inventory image size
2889 // is 0.53 inch multiplied by the gui_scaling
2890 // config parameter. This magic size is chosen
2891 // to make the main menu (15.5 inventory images
2892 // wide, including border) just fit into the
2893 // default window (800 pixels wide) at 96 DPI
2894 // and default scaling (1.00).
2895 use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2897 // In variable-size mode, we prefer to make the
2898 // inventory image size 1/15 of screen height,
2899 // multiplied by the gui_scaling config parameter.
2900 // If the preferred size won't fit the whole
2901 // form on the screen, either horizontally or
2902 // vertically, then we scale it down to fit.
2903 // (The magic numbers in the computation of what
2904 // fits arise from the scaling factors in the
2905 // following stanza, including the form border,
2906 // help text space, and 0.1 inventory slot spare.)
2907 // However, a minimum size is also set, that
2908 // the image size can't be less than 0.3 inch
2909 // multiplied by gui_scaling, even if this means
2910 // the form doesn't fit the screen.
2912 // For mobile devices these magic numbers are
2913 // different and forms should always use the
2914 // maximum screen space available.
2915 double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
2916 double fitx_imgsize = mydata.screensize.X /
2917 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
2918 double fity_imgsize = mydata.screensize.Y /
2919 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
2920 use_imgsize = MYMIN(prefer_imgsize,
2921 MYMIN(fitx_imgsize, fity_imgsize));
2923 double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
2924 double fitx_imgsize = mydata.screensize.X /
2925 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
2926 double fity_imgsize = mydata.screensize.Y /
2927 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
2928 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2929 double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2930 use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2931 MYMIN(fitx_imgsize, fity_imgsize)));
2935 // Everything else is scaled in proportion to the
2936 // inventory image size. The inventory slot spacing
2937 // is 5/4 image size horizontally and 15/13 image size
2938 // vertically. The padding around the form (incorporating
2939 // the border of the outer inventory slots) is 3/8
2940 // image size. Font height (baseline to baseline)
2941 // is 2/5 vertical inventory slot spacing, and button
2942 // half-height is 7/8 of font height.
2943 imgsize = v2s32(use_imgsize, use_imgsize);
2944 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2945 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2946 m_btn_height = use_imgsize*15.0/13 * 0.35;
2948 m_font = g_fontengine->getFont();
2950 if (mydata.real_coordinates) {
2951 mydata.size = v2s32(
2952 mydata.invsize.X*imgsize.X,
2953 mydata.invsize.Y*imgsize.Y
2956 mydata.size = v2s32(
2957 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2958 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2962 DesiredRect = mydata.rect = core::rect<s32>(
2963 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2964 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2965 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2966 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2969 // Non-size[] form must consist only of text fields and
2970 // implicit "Proceed" button. Use default font, and
2971 // temporary form size which will be recalculated below.
2972 m_font = g_fontengine->getFont();
2973 m_btn_height = font_line_height(m_font) * 0.875;
2974 DesiredRect = core::rect<s32>(
2975 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2976 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2977 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2978 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2981 recalculateAbsolutePosition(false);
2982 mydata.basepos = getBasePos();
2983 m_tooltip_element->setOverrideFont(m_font);
2985 gui::IGUISkin *skin = Environment->getSkin();
2987 gui::IGUIFont *old_font = skin->getFont();
2988 skin->setFont(m_font);
2990 pos_offset = v2f32();
2992 // used for formspec versions < 3
2993 core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
2995 if (enable_prepends) {
2996 // Backup the coordinates so that prepends can use the coordinates of choice.
2997 bool rc_backup = mydata.real_coordinates;
2998 u16 version_backup = m_formspec_version;
2999 mydata.real_coordinates = false; // Old coordinates by default.
3001 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3002 for (const auto &element : prepend_elements)
3003 parseElement(&mydata, element);
3005 // legacy sorting for formspec versions < 3
3006 if (m_formspec_version >= 3)
3007 // prepends do not need to be reordered
3008 legacy_sort_start = Children.getLast();
3009 else if (version_backup >= 3)
3010 // only prepends elements have to be reordered
3011 legacySortElements(legacy_sort_start);
3013 m_formspec_version = version_backup;
3014 mydata.real_coordinates = rc_backup; // Restore coordinates
3017 for (; i< elements.size(); i++) {
3018 parseElement(&mydata, elements[i]);
3021 if (!container_stack.empty()) {
3022 errorstream << "Invalid formspec string: container was never closed!"
3026 // If there are fields without explicit size[], add a "Proceed"
3027 // button and adjust size to fit all the fields.
3028 if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3029 mydata.rect = core::rect<s32>(
3030 mydata.screensize.X / 2 - 580 / 2,
3031 mydata.screensize.Y / 2 - 300 / 2,
3032 mydata.screensize.X / 2 + 580 / 2,
3033 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3036 DesiredRect = mydata.rect;
3037 recalculateAbsolutePosition(false);
3038 mydata.basepos = getBasePos();
3041 v2s32 pos = mydata.basepos;
3042 pos.Y = (mydata.simple_field_count + 2) * 60;
3044 v2s32 size = DesiredRect.getSize();
3045 mydata.rect = core::rect<s32>(
3046 size.X / 2 - 70, pos.Y,
3047 size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3049 const wchar_t *text = wgettext("Proceed");
3050 GUIButton::addButton(Environment, mydata.rect, this, 257, text);
3055 //set initial focus if parser didn't set it
3056 focused_element = Environment->getFocus();
3057 if (!focused_element
3058 || !isMyChild(focused_element)
3059 || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3062 skin->setFont(old_font);
3065 if (m_formspec_version < 3)
3066 legacySortElements(legacy_sort_start);
3069 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3072 Draw order for formspec_version <= 2:
3076 0 All other elements
3078 2 item_image, item_image_button
3083 if (from == Children.end())
3084 from = Children.begin();
3088 core::list<IGUIElement *>::Iterator to = Children.end();
3089 // 1: Copy into a sortable container
3090 std::vector<IGUIElement *> elements;
3091 for (auto it = from; it != to; ++it)
3092 elements.emplace_back(*it);
3094 // 2: Sort the container
3095 std::sort(elements.begin(), elements.end(),
3096 [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3097 const FieldSpec *spec_a = getSpecByID(a->getID());
3098 const FieldSpec *spec_b = getSpecByID(b->getID());
3099 return spec_a && spec_b &&
3100 spec_a->priority < spec_b->priority;
3103 // 3: Re-assign the pointers
3104 for (auto e : elements) {
3111 bool GUIFormSpecMenu::getAndroidUIInput()
3113 if (!hasAndroidUIInput())
3116 std::string fieldname = m_jni_field_name;
3117 m_jni_field_name.clear();
3119 for(std::vector<FieldSpec>::iterator iter = m_fields.begin();
3120 iter != m_fields.end(); ++iter) {
3122 if (iter->fname != fieldname) {
3125 IGUIElement *tochange = getElementFromId(iter->fid, true);
3127 if (tochange == 0) {
3131 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
3135 std::string text = porting::getInputDialogValue();
3137 ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
3143 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3145 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3147 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3148 core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3149 v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3150 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
3151 s32 item_i = i + s.start_item_i;
3155 if (s.real_coordinates) {
3156 x = (i%s.geom.X) * (imgsize.X * 1.25);
3157 y = (i/s.geom.X) * (imgsize.Y * 1.25);
3159 x = (i%s.geom.X) * spacing.X;
3160 y = (i/s.geom.X) * spacing.Y;
3163 core::rect<s32> rect = imgrect + base_pos + p0;
3164 rect.clipAgainst(clipping_rect);
3165 if (rect.getArea() > 0 && rect.isPointInside(p))
3166 return ItemSpec(s.inventoryloc, s.listname, item_i);
3170 return ItemSpec(InventoryLocation(), "", -1);
3173 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer,
3176 video::IVideoDriver* driver = Environment->getVideoDriver();
3178 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3180 warningstream<<"GUIFormSpecMenu::drawList(): "
3181 << "The inventory location "
3182 << "\"" << s.inventoryloc.dump() << "\" doesn't exist anymore"
3186 InventoryList *ilist = inv->getList(s.listname);
3188 warningstream << "GUIFormSpecMenu::drawList(): "
3189 << "The inventory list \"" << s.listname << "\" @ \""
3190 << s.inventoryloc.dump() << "\" doesn't exist anymore"
3195 core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3196 core::rect<s32> clipping_rect = s.e->getAbsoluteClippingRect();
3197 v2s32 base_pos = s.e->getAbsolutePosition().UpperLeftCorner;
3199 for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) {
3200 s32 item_i = i + s.start_item_i;
3201 if (item_i >= (s32)ilist->getSize())
3206 if (s.real_coordinates) {
3207 x = (i%s.geom.X) * (imgsize.X * 1.25);
3208 y = (i/s.geom.X) * (imgsize.Y * 1.25);
3210 x = (i%s.geom.X) * spacing.X;
3211 y = (i/s.geom.X) * spacing.Y;
3214 core::rect<s32> rect = imgrect + base_pos + p;
3215 ItemStack item = ilist->getItem(item_i);
3217 bool selected = m_selected_item
3218 && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
3219 && m_selected_item->listname == s.listname
3220 && m_selected_item->i == item_i;
3221 core::rect<s32> clipped_rect(rect);
3222 clipped_rect.clipAgainst(clipping_rect);
3223 bool hovering = clipped_rect.getArea() > 0 &&
3224 clipped_rect.isPointInside(m_pointer);
3225 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
3226 (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
3230 item_hovered = true;
3231 driver->draw2DRectangle(m_slotbg_h, rect, &clipping_rect);
3233 driver->draw2DRectangle(m_slotbg_n, rect, &clipping_rect);
3237 //Draw inv slot borders
3239 s32 x1 = rect.UpperLeftCorner.X;
3240 s32 y1 = rect.UpperLeftCorner.Y;
3241 s32 x2 = rect.LowerRightCorner.X;
3242 s32 y2 = rect.LowerRightCorner.Y;
3244 driver->draw2DRectangle(m_slotbordercolor,
3245 core::rect<s32>(v2s32(x1 - border, y1 - border),
3246 v2s32(x2 + border, y1)), &clipping_rect);
3247 driver->draw2DRectangle(m_slotbordercolor,
3248 core::rect<s32>(v2s32(x1 - border, y2),
3249 v2s32(x2 + border, y2 + border)), &clipping_rect);
3250 driver->draw2DRectangle(m_slotbordercolor,
3251 core::rect<s32>(v2s32(x1 - border, y1),
3252 v2s32(x1, y2)), &clipping_rect);
3253 driver->draw2DRectangle(m_slotbordercolor,
3254 core::rect<s32>(v2s32(x2, y1),
3255 v2s32(x2 + border, y2)), &clipping_rect);
3260 item.takeItem(m_selected_amount);
3262 if (!item.empty()) {
3264 drawItemStack(driver, m_font, item,
3265 rect, &clipping_rect, m_client, rotation_kind);
3267 if (hovering && !m_selected_item) {
3268 std::string tooltip = item.getDescription(m_client->idef());
3269 if (m_tooltip_append_itemname)
3270 tooltip += "\n[" + item.name + "]";
3271 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3272 m_default_tooltip_bgcolor);
3279 void GUIFormSpecMenu::drawSelectedItem()
3281 video::IVideoDriver* driver = Environment->getVideoDriver();
3283 if (!m_selected_item) {
3284 // reset rotation time
3285 drawItemStack(driver, m_font, ItemStack(),
3286 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3287 m_client, IT_ROT_DRAGGED);
3291 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3293 InventoryList *list = inv->getList(m_selected_item->listname);
3295 ItemStack stack = list->getItem(m_selected_item->i);
3296 stack.count = m_selected_amount;
3298 core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3299 core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3300 rect.constrainTo(driver->getViewPort());
3301 drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3304 void GUIFormSpecMenu::drawMenu()
3307 const std::string &newform = m_form_src->getForm();
3308 if (newform != m_formspec_string) {
3309 m_formspec_string = newform;
3310 regenerateGui(m_screensize_old);
3314 gui::IGUISkin* skin = Environment->getSkin();
3315 sanity_check(skin != NULL);
3316 gui::IGUIFont *old_font = skin->getFont();
3317 skin->setFont(m_font);
3319 updateSelectedItem();
3321 video::IVideoDriver* driver = Environment->getVideoDriver();
3324 Draw background color
3326 v2u32 screenSize = driver->getScreenSize();
3327 core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3330 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3331 if (m_bgnonfullscreen)
3332 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3335 Draw rect_mode tooltip
3337 m_tooltip_element->setVisible(false);
3339 for (const auto &pair : m_tooltip_rects) {
3340 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3341 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3342 const std::wstring &text = pair.second.tooltip;
3343 if (!text.empty()) {
3344 showTooltip(text, pair.second.color, pair.second.bgcolor);
3353 for (gui::IGUIElement *e : m_backgrounds) {
3354 e->setVisible(true);
3356 e->setVisible(false);
3362 gui::IGUIElement::draw();
3366 Layer 0: Item slot rectangles
3367 Layer 1: Item images; prepare tooltip
3369 bool item_hovered = false;
3370 for (int layer = 0; layer < 2; layer++) {
3371 for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
3372 drawList(spec, layer, item_hovered);
3375 if (!item_hovered) {
3376 // reset rotation time
3377 drawItemStack(driver, m_font, ItemStack(),
3378 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3379 NULL, m_client, IT_ROT_HOVERED);
3382 /* TODO find way to show tooltips on touchscreen */
3383 #ifndef HAVE_TOUCHSCREENGUI
3384 m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3388 Draw fields/buttons tooltips
3390 gui::IGUIElement *hovered =
3391 Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3393 if (hovered != NULL) {
3394 s32 id = hovered->getID();
3398 m_old_tooltip_id = id;
3400 if (id == m_old_tooltip_id) {
3401 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3403 m_hovered_time = porting::getTimeMs();
3404 m_old_tooltip_id = id;
3408 // Find and update the current tooltip
3409 if (id != -1 && delta >= m_tooltip_show_delay) {
3410 for (const FieldSpec &field : m_fields) {
3412 if (field.fid != id)
3415 const std::wstring &text = m_tooltips[field.fname].tooltip;
3417 showTooltip(text, m_tooltips[field.fname].color,
3418 m_tooltips[field.fname].bgcolor);
3425 m_tooltip_element->draw();
3428 Draw dragged item stack
3432 skin->setFont(old_font);
3436 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3437 const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3439 const std::wstring ntext = translate_string(text);
3440 m_tooltip_element->setOverrideColor(color);
3441 m_tooltip_element->setBackgroundColor(bgcolor);
3442 setStaticText(m_tooltip_element, ntext.c_str());
3444 // Tooltip size and offset
3445 s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3446 #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
3447 std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
3448 s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
3450 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3452 v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3453 int tooltip_offset_x = m_btn_height;
3454 int tooltip_offset_y = m_btn_height;
3456 tooltip_offset_x *= 3;
3457 tooltip_offset_y = 0;
3458 if (m_pointer.X > (s32)screenSize.X / 2)
3459 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3462 // Calculate and set the tooltip position
3463 s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3464 s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3465 if (tooltip_x + tooltip_width > (s32)screenSize.X)
3466 tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height;
3467 if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3468 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3470 m_tooltip_element->setRelativePosition(
3472 core::position2d<s32>(tooltip_x, tooltip_y),
3473 core::dimension2d<s32>(tooltip_width, tooltip_height)
3477 // Display the tooltip
3478 m_tooltip_element->setVisible(true);
3479 bringToFront(m_tooltip_element);
3482 void GUIFormSpecMenu::updateSelectedItem()
3484 verifySelectedItem();
3486 // If craftresult is nonempty and nothing else is selected, select it now.
3487 if (!m_selected_item) {
3488 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
3489 if (s.listname != "craftpreview")
3492 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
3496 InventoryList *list = inv->getList("craftresult");
3498 if (!list || list->getSize() == 0)
3501 const ItemStack &item = list->getItem(0);
3505 // Grab selected item from the crafting result list
3506 m_selected_item = new ItemSpec;
3507 m_selected_item->inventoryloc = s.inventoryloc;
3508 m_selected_item->listname = "craftresult";
3509 m_selected_item->i = 0;
3510 m_selected_amount = item.count;
3511 m_selected_dragging = false;
3516 // If craftresult is selected, keep the whole stack selected
3517 if (m_selected_item && m_selected_item->listname == "craftresult")
3518 m_selected_amount = verifySelectedItem().count;
3521 ItemStack GUIFormSpecMenu::verifySelectedItem()
3523 // If the selected stack has become empty for some reason, deselect it.
3524 // If the selected stack has become inaccessible, deselect it.
3525 // If the selected stack has become smaller, adjust m_selected_amount.
3526 // Return the selected stack.
3530 if(m_selected_item->isValid())
3532 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3535 InventoryList *list = inv->getList(m_selected_item->listname);
3536 if(list && (u32) m_selected_item->i < list->getSize())
3538 ItemStack stack = list->getItem(m_selected_item->i);
3539 if (!m_selected_swap.empty()) {
3540 if (m_selected_swap.name == stack.name &&
3541 m_selected_swap.count == stack.count)
3542 m_selected_swap.clear();
3544 m_selected_amount = std::min(m_selected_amount, stack.count);
3553 // selection was not valid
3554 delete m_selected_item;
3555 m_selected_item = NULL;
3556 m_selected_amount = 0;
3557 m_selected_dragging = false;
3562 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3568 if (quitmode == quit_mode_accept) {
3569 fields["quit"] = "true";
3572 if (quitmode == quit_mode_cancel) {
3573 fields["quit"] = "true";
3574 m_text_dst->gotText(fields);
3578 if (current_keys_pending.key_down) {
3579 fields["key_down"] = "true";
3580 current_keys_pending.key_down = false;
3583 if (current_keys_pending.key_up) {
3584 fields["key_up"] = "true";
3585 current_keys_pending.key_up = false;
3588 if (current_keys_pending.key_enter) {
3589 fields["key_enter"] = "true";
3590 current_keys_pending.key_enter = false;
3593 if (!current_field_enter_pending.empty()) {
3594 fields["key_enter_field"] = current_field_enter_pending;
3595 current_field_enter_pending = "";
3598 if (current_keys_pending.key_escape) {
3599 fields["key_escape"] = "true";
3600 current_keys_pending.key_escape = false;
3603 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3605 std::string name = s.fname;
3606 if (s.ftype == f_Button) {
3607 fields[name] = wide_to_utf8(s.flabel);
3608 } else if (s.ftype == f_Table) {
3609 GUITable *table = getTable(s.fname);
3611 fields[name] = table->checkEvent();
3614 else if(s.ftype == f_DropDown) {
3615 // no dynamic cast possible due to some distributions shipped
3616 // without rtti support in irrlicht
3617 IGUIElement *element = getElementFromId(s.fid, true);
3618 gui::IGUIComboBox *e = NULL;
3619 if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3620 e = static_cast<gui::IGUIComboBox*>(element);
3622 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3623 << "field without dropdown element" << std::endl;
3626 s32 selected = e->getSelected();
3627 if (selected >= 0) {
3628 std::vector<std::string> *dropdown_values =
3629 getDropDownValues(s.fname);
3630 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3631 fields[name] = (*dropdown_values)[selected];
3635 else if (s.ftype == f_TabHeader) {
3636 // no dynamic cast possible due to some distributions shipped
3637 // without rttzi support in irrlicht
3638 IGUIElement *element = getElementFromId(s.fid, true);
3639 gui::IGUITabControl *e = nullptr;
3640 if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3641 e = static_cast<gui::IGUITabControl *>(element);
3645 std::stringstream ss;
3646 ss << (e->getActiveTab() +1);
3647 fields[name] = ss.str();
3650 else if (s.ftype == f_CheckBox) {
3651 // no dynamic cast possible due to some distributions shipped
3652 // without rtti support in irrlicht
3653 IGUIElement *element = getElementFromId(s.fid, true);
3654 gui::IGUICheckBox *e = nullptr;
3655 if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3656 e = static_cast<gui::IGUICheckBox*>(element);
3661 fields[name] = "true";
3663 fields[name] = "false";
3666 else if (s.ftype == f_ScrollBar) {
3667 // no dynamic cast possible due to some distributions shipped
3668 // without rtti support in irrlicht
3669 IGUIElement *element = getElementFromId(s.fid, true);
3670 GUIScrollBar *e = nullptr;
3671 if (element && element->getType() == gui::EGUIET_ELEMENT)
3672 e = static_cast<GUIScrollBar *>(element);
3675 std::stringstream os;
3677 if (s.fdefault == L"Changed")
3678 fields[name] = "CHG:" + os.str();
3680 fields[name] = "VAL:" + os.str();
3684 IGUIElement *e = getElementFromId(s.fid, true);
3686 fields[name] = wide_to_utf8(e->getText());
3691 m_text_dst->gotText(fields);
3695 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
3697 while(tocheck != NULL) {
3698 if (tocheck == parent) {
3701 tocheck = tocheck->getParent();
3706 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3708 // The IGUITabControl renders visually using the skin's selected
3709 // font, which we override for the duration of form drawing,
3710 // but computes tab hotspots based on how it would have rendered
3711 // using the font that is selected at the time of button release.
3712 // To make these two consistent, temporarily override the skin's
3713 // font while the IGUITabControl is processing the event.
3714 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3715 event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3716 s32 x = event.MouseInput.X;
3717 s32 y = event.MouseInput.Y;
3718 gui::IGUIElement *hovered =
3719 Environment->getRootGUIElement()->getElementFromPoint(
3720 core::position2d<s32>(x, y));
3721 if (hovered && isMyChild(hovered) &&
3722 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3723 gui::IGUISkin* skin = Environment->getSkin();
3724 sanity_check(skin != NULL);
3725 gui::IGUIFont *old_font = skin->getFont();
3726 skin->setFont(m_font);
3727 bool retval = hovered->OnEvent(event);
3728 skin->setFont(old_font);
3733 // Fix Esc/Return key being eaten by checkboxen and tables
3734 if(event.EventType==EET_KEY_INPUT_EVENT) {
3735 KeyPress kp(event.KeyInput);
3736 if (kp == EscapeKey || kp == CancelKey
3737 || kp == getKeySetting("keymap_inventory")
3738 || event.KeyInput.Key==KEY_RETURN) {
3739 gui::IGUIElement *focused = Environment->getFocus();
3740 if (focused && isMyChild(focused) &&
3741 (focused->getType() == gui::EGUIET_LIST_BOX ||
3742 focused->getType() == gui::EGUIET_CHECK_BOX) &&
3743 (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3744 event.KeyInput.Key != KEY_RETURN)) {
3750 // Mouse wheel and move events: send to hovered element instead of focused
3751 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3752 (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3753 event.MouseInput.Event == EMIE_MOUSE_MOVED)) {
3754 s32 x = event.MouseInput.X;
3755 s32 y = event.MouseInput.Y;
3756 gui::IGUIElement *hovered =
3757 Environment->getRootGUIElement()->getElementFromPoint(
3758 core::position2d<s32>(x, y));
3759 if (hovered && isMyChild(hovered)) {
3760 hovered->OnEvent(event);
3761 return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3765 if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3766 s32 x = event.MouseInput.X;
3767 s32 y = event.MouseInput.Y;
3768 gui::IGUIElement *hovered =
3769 Environment->getRootGUIElement()->getElementFromPoint(
3770 core::position2d<s32>(x, y));
3771 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3772 m_old_tooltip_id = -1;
3774 if (!isChild(hovered,this)) {
3775 if (DoubleClickDetection(event)) {
3781 if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3782 /* TODO add a check like:
3783 if (event.JoystickEvent != joystick_we_listen_for)
3786 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3788 if (m_joystick->wasKeyDown(KeyType::ESC)) {
3790 } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3792 acceptInput(quit_mode_accept);
3800 return GUIModalMenu::preprocessEvent(event);
3803 /******************************************************************************/
3804 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3806 /* The following code is for capturing double-clicks of the mouse button
3807 * and translating the double-click into an EET_KEY_INPUT_EVENT event
3808 * -- which closes the form -- under some circumstances.
3810 * There have been many github issues reporting this as a bug even though it
3811 * was an intended feature. For this reason, remapping the double-click as
3812 * an ESC must be explicitly set when creating this class via the
3813 * /p remap_dbl_click parameter of the constructor.
3816 if (!m_remap_dbl_click)
3819 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3820 m_doubleclickdetect[0].pos = m_doubleclickdetect[1].pos;
3821 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3823 m_doubleclickdetect[1].pos = m_pointer;
3824 m_doubleclickdetect[1].time = porting::getTimeMs();
3826 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3827 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3832 double squaredistance =
3833 m_doubleclickdetect[0].pos
3834 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3836 if (squaredistance > (30*30)) {
3840 SEvent* translated = new SEvent();
3841 assert(translated != 0);
3842 //translate doubleclick to escape
3843 memset(translated, 0, sizeof(SEvent));
3844 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3845 translated->KeyInput.Key = KEY_ESCAPE;
3846 translated->KeyInput.Control = false;
3847 translated->KeyInput.Shift = false;
3848 translated->KeyInput.PressedDown = true;
3849 translated->KeyInput.Char = 0;
3850 OnEvent(*translated);
3852 // no need to send the key up event as we're already deleted
3853 // and no one else did notice this event
3861 void GUIFormSpecMenu::tryClose()
3865 acceptInput(quit_mode_cancel);
3868 m_text_dst->gotText(L"MenuQuit");
3872 enum ButtonEventType : u8
3885 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3887 if (event.EventType==EET_KEY_INPUT_EVENT) {
3888 KeyPress kp(event.KeyInput);
3889 if (event.KeyInput.PressedDown && (
3890 (kp == EscapeKey) || (kp == CancelKey) ||
3891 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3896 if (m_client != NULL && event.KeyInput.PressedDown &&
3897 (kp == getKeySetting("keymap_screenshot"))) {
3898 m_client->makeScreenshot();
3900 if (event.KeyInput.PressedDown &&
3901 (event.KeyInput.Key==KEY_RETURN ||
3902 event.KeyInput.Key==KEY_UP ||
3903 event.KeyInput.Key==KEY_DOWN)
3905 switch (event.KeyInput.Key) {
3907 current_keys_pending.key_enter = true;
3910 current_keys_pending.key_up = true;
3913 current_keys_pending.key_down = true;
3917 //can't happen at all!
3918 FATAL_ERROR("Reached a source line that can't ever been reached");
3921 if (current_keys_pending.key_enter && m_allowclose) {
3922 acceptInput(quit_mode_accept);
3932 /* Mouse event other than movement, or crossing the border of inventory
3933 field while holding right mouse button
3935 if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3936 (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3937 (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3938 event.MouseInput.isRightPressed() &&
3939 getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3941 // Get selected item and hovered/clicked item (s)
3943 m_old_tooltip_id = -1;
3944 updateSelectedItem();
3945 ItemSpec s = getItemAtPos(m_pointer);
3947 Inventory *inv_selected = NULL;
3948 Inventory *inv_s = NULL;
3949 InventoryList *list_s = NULL;
3951 if (m_selected_item) {
3952 inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3953 sanity_check(inv_selected);
3954 sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3961 inv_s = m_invmgr->getInventory(s.inventoryloc);
3964 errorstream << "InventoryMenu: The selected inventory location "
3965 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3967 s.i = -1; // make it invalid again
3971 list_s = inv_s->getList(s.listname);
3972 if (list_s == NULL) {
3973 verbosestream << "InventoryMenu: The selected inventory list \""
3974 << s.listname << "\" does not exist" << std::endl;
3975 s.i = -1; // make it invalid again
3979 if ((u32)s.i >= list_s->getSize()) {
3980 infostream << "InventoryMenu: The selected inventory list \""
3981 << s.listname << "\" is too small (i=" << s.i << ", size="
3982 << list_s->getSize() << ")" << std::endl;
3983 s.i = -1; // make it invalid again
3987 s_count = list_s->getItem(s.i).count;
3990 bool identical = m_selected_item && s.isValid() &&
3991 (inv_selected == inv_s) &&
3992 (m_selected_item->listname == s.listname) &&
3993 (m_selected_item->i == s.i);
3995 ButtonEventType button = BET_LEFT;
3996 ButtonEventType updown = BET_OTHER;
3997 switch (event.MouseInput.Event) {
3998 case EMIE_LMOUSE_PRESSED_DOWN:
3999 button = BET_LEFT; updown = BET_DOWN;
4001 case EMIE_RMOUSE_PRESSED_DOWN:
4002 button = BET_RIGHT; updown = BET_DOWN;
4004 case EMIE_MMOUSE_PRESSED_DOWN:
4005 button = BET_MIDDLE; updown = BET_DOWN;
4007 case EMIE_MOUSE_WHEEL:
4008 button = (event.MouseInput.Wheel > 0) ?
4009 BET_WHEEL_UP : BET_WHEEL_DOWN;
4012 case EMIE_LMOUSE_LEFT_UP:
4013 button = BET_LEFT; updown = BET_UP;
4015 case EMIE_RMOUSE_LEFT_UP:
4016 button = BET_RIGHT; updown = BET_UP;
4018 case EMIE_MMOUSE_LEFT_UP:
4019 button = BET_MIDDLE; updown = BET_UP;
4021 case EMIE_MOUSE_MOVED:
4028 // Set this number to a positive value to generate a move action
4029 // from m_selected_item to s.
4030 u32 move_amount = 0;
4032 // Set this number to a positive value to generate a move action
4033 // from s to the next inventory ring.
4034 u32 shift_move_amount = 0;
4036 // Set this number to a positive value to generate a drop action
4037 // from m_selected_item.
4038 u32 drop_amount = 0;
4040 // Set this number to a positive value to generate a craft action at s.
4041 u32 craft_amount = 0;
4045 // Some mouse button has been pressed
4047 //infostream<<"Mouse button "<<button<<" pressed at p=("
4048 // <<p.X<<","<<p.Y<<")"<<std::endl;
4050 m_selected_dragging = false;
4052 if (s.isValid() && s.listname == "craftpreview") {
4053 // Craft preview has been clicked: craft
4054 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4055 } else if (!m_selected_item) {
4056 if (s_count && button != BET_WHEEL_UP) {
4057 // Non-empty stack has been clicked: select or shift-move it
4058 m_selected_item = new ItemSpec(s);
4061 if (button == BET_RIGHT)
4062 count = (s_count + 1) / 2;
4063 else if (button == BET_MIDDLE)
4064 count = MYMIN(s_count, 10);
4065 else if (button == BET_WHEEL_DOWN)
4070 if (!event.MouseInput.Shift) {
4071 // no shift: select item
4072 m_selected_amount = count;
4073 m_selected_dragging = button != BET_WHEEL_DOWN;
4074 m_auto_place = false;
4076 // shift pressed: move item, right click moves 1
4077 shift_move_amount = button == BET_RIGHT ? 1 : count;
4080 } else { // m_selected_item != NULL
4081 assert(m_selected_amount >= 1);
4084 // Clicked a slot: move
4085 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4087 else if (button == BET_MIDDLE)
4088 move_amount = MYMIN(m_selected_amount, 10);
4089 else if (button == BET_LEFT)
4090 move_amount = m_selected_amount;
4094 if (button == BET_WHEEL_DOWN) {
4095 if (m_selected_amount < s_count)
4096 ++m_selected_amount;
4098 if (move_amount >= m_selected_amount)
4099 m_selected_amount = 0;
4101 m_selected_amount -= move_amount;
4105 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4106 && button != BET_WHEEL_DOWN) {
4107 // Clicked outside of the window: drop
4108 if (button == BET_RIGHT || button == BET_WHEEL_UP)
4110 else if (button == BET_MIDDLE)
4111 drop_amount = MYMIN(m_selected_amount, 10);
4113 drop_amount = m_selected_amount;
4118 // Some mouse button has been released
4120 //infostream<<"Mouse button "<<button<<" released at p=("
4121 // <<p.X<<","<<p.Y<<")"<<std::endl;
4123 if (m_selected_dragging && m_selected_item) {
4126 // Dragged to different slot: move all selected
4127 move_amount = m_selected_amount;
4129 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4130 // Dragged outside of window: drop all selected
4131 drop_amount = m_selected_amount;
4135 m_selected_dragging = false;
4136 // Keep track of whether the mouse button be released
4137 // One click is drag without dropping. Click + release
4138 // + click changes to drop item when moved mode
4139 if (m_selected_item)
4140 m_auto_place = true;
4143 // Mouse has been moved and rmb is down and mouse pointer just
4144 // entered a new inventory field (checked in the entry-if, this
4145 // is the only action here that is generated by mouse movement)
4146 if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4148 // TODO: middle mouse to move 10 items might be handy
4150 // Only move an item if the destination slot is empty
4151 // or contains the same item type as what is going to be
4153 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4154 InventoryList *list_to = list_s;
4155 assert(list_from && list_to);
4156 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4157 ItemStack stack_to = list_to->getItem(s.i);
4158 if (stack_to.empty() || stack_to.name == stack_from.name)
4167 // Possibly send inventory action to server
4168 if (move_amount > 0) {
4169 // Send IAction::Move
4171 assert(m_selected_item && m_selected_item->isValid());
4172 assert(s.isValid());
4174 assert(inv_selected && inv_s);
4175 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4176 InventoryList *list_to = list_s;
4177 assert(list_from && list_to);
4178 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4179 ItemStack stack_to = list_to->getItem(s.i);
4181 // Check how many items can be moved
4182 move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4183 ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4185 // If source stack cannot be added to destination stack at all,
4187 if (leftover.count == stack_from.count &&
4188 leftover.name == stack_from.name) {
4190 if (m_selected_swap.empty()) {
4191 m_selected_amount = stack_to.count;
4192 m_selected_dragging = false;
4194 // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4195 // Skip next validation checks due async inventory calls
4196 m_selected_swap = stack_to;
4201 // Source stack goes fully into destination stack
4202 else if (leftover.empty()) {
4203 m_selected_amount -= move_amount;
4205 // Source stack goes partly into destination stack
4207 move_amount -= leftover.count;
4208 m_selected_amount -= move_amount;
4212 infostream << "Handing IAction::Move to manager" << std::endl;
4213 IMoveAction *a = new IMoveAction();
4214 a->count = move_amount;
4215 a->from_inv = m_selected_item->inventoryloc;
4216 a->from_list = m_selected_item->listname;
4217 a->from_i = m_selected_item->i;
4218 a->to_inv = s.inventoryloc;
4219 a->to_list = s.listname;
4221 m_invmgr->inventoryAction(a);
4223 } else if (shift_move_amount > 0) {
4224 u32 mis = m_inventory_rings.size();
4226 for (; i < mis; i++) {
4227 const ListRingSpec &sp = m_inventory_rings[i];
4228 if (sp.inventoryloc == s.inventoryloc
4229 && sp.listname == s.listname)
4233 if (i >= mis) // if not found
4235 u32 to_inv_ind = (i + 1) % mis;
4236 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4237 InventoryList *list_from = list_s;
4240 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4243 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4246 ItemStack stack_from = list_from->getItem(s.i);
4247 assert(shift_move_amount <= stack_from.count);
4249 infostream << "Handing IAction::Move to manager" << std::endl;
4250 IMoveAction *a = new IMoveAction();
4251 a->count = shift_move_amount;
4252 a->from_inv = s.inventoryloc;
4253 a->from_list = s.listname;
4255 a->to_inv = to_inv_sp.inventoryloc;
4256 a->to_list = to_inv_sp.listname;
4257 a->move_somewhere = true;
4258 m_invmgr->inventoryAction(a);
4260 } else if (drop_amount > 0) {
4261 // Send IAction::Drop
4263 assert(m_selected_item && m_selected_item->isValid());
4264 assert(inv_selected);
4265 InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4267 ItemStack stack_from = list_from->getItem(m_selected_item->i);
4269 // Check how many items can be dropped
4270 drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4271 assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4272 m_selected_amount -= drop_amount;
4274 infostream << "Handing IAction::Drop to manager" << std::endl;
4275 IDropAction *a = new IDropAction();
4276 a->count = drop_amount;
4277 a->from_inv = m_selected_item->inventoryloc;
4278 a->from_list = m_selected_item->listname;
4279 a->from_i = m_selected_item->i;
4280 m_invmgr->inventoryAction(a);
4281 } else if (craft_amount > 0) {
4282 assert(s.isValid());
4284 // if there are no items selected or the selected item
4285 // belongs to craftresult list, proceed with crafting
4286 if (m_selected_item == NULL ||
4287 !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4291 // Send IACTION_CRAFT
4292 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4293 ICraftAction *a = new ICraftAction();
4294 a->count = craft_amount;
4295 a->craft_inv = s.inventoryloc;
4296 m_invmgr->inventoryAction(a);
4300 // If m_selected_amount has been decreased to zero, deselect
4301 if (m_selected_amount == 0) {
4302 m_selected_swap.clear();
4303 delete m_selected_item;
4304 m_selected_item = NULL;
4305 m_selected_amount = 0;
4306 m_selected_dragging = false;
4308 m_old_pointer = m_pointer;
4311 if (event.EventType == EET_GUI_EVENT) {
4312 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4314 // find the element that was clicked
4315 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4316 if ((s.ftype == f_TabHeader) &&
4317 (s.fid == event.GUIEvent.Caller->getID())) {
4325 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4327 if (!canTakeFocus(event.GUIEvent.Element)) {
4328 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4330 // Returning true disables focus change
4334 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4335 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4336 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4337 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4338 unsigned int btn_id = event.GUIEvent.Caller->getID();
4340 if (btn_id == 257) {
4342 acceptInput(quit_mode_accept);
4346 m_text_dst->gotText(L"ExitButton");
4348 // quitMenu deallocates menu
4352 // find the element that was clicked
4353 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4354 // if its a button, set the send field so
4355 // lua knows which button was pressed
4356 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
4357 s.fid == event.GUIEvent.Caller->getID()) {
4361 acceptInput(quit_mode_accept);
4364 m_text_dst->gotText(L"ExitButton");
4369 acceptInput(quit_mode_no);
4373 } else if ((s.ftype == f_DropDown) &&
4374 (s.fid == event.GUIEvent.Caller->getID())) {
4375 // only send the changed dropdown
4376 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4377 if (s2.ftype == f_DropDown) {
4382 acceptInput(quit_mode_no);
4384 // revert configuration to make sure dropdowns are sent on
4385 // regular button click
4386 for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4387 if (s2.ftype == f_DropDown) {
4392 } else if ((s.ftype == f_ScrollBar) &&
4393 (s.fid == event.GUIEvent.Caller->getID())) {
4394 s.fdefault = L"Changed";
4395 acceptInput(quit_mode_no);
4397 } else if ((s.ftype == f_Unknown) &&
4398 (s.fid == event.GUIEvent.Caller->getID())) {
4406 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4407 if (event.GUIEvent.Caller->getID() > 257) {
4408 bool close_on_enter = true;
4409 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4410 if (s.ftype == f_Unknown &&
4411 s.fid == event.GUIEvent.Caller->getID()) {
4412 current_field_enter_pending = s.fname;
4413 std::unordered_map<std::string, bool>::const_iterator it =
4414 field_close_on_enter.find(s.fname);
4415 if (it != field_close_on_enter.end())
4416 close_on_enter = (*it).second;
4422 if (m_allowclose && close_on_enter) {
4423 current_keys_pending.key_enter = true;
4424 acceptInput(quit_mode_accept);
4427 current_keys_pending.key_enter = true;
4430 // quitMenu deallocates menu
4435 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4436 int current_id = event.GUIEvent.Caller->getID();
4437 if (current_id > 257) {
4438 // find the element that was clicked
4439 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4440 // if it's a table, set the send field
4441 // so lua knows which table was changed
4442 if ((s.ftype == f_Table) && (s.fid == current_id)) {
4453 return Parent ? Parent->OnEvent(event) : false;
4457 * get name of element by element id
4458 * @param id of element
4459 * @return name string or empty string
4461 std::string GUIFormSpecMenu::getNameByID(s32 id)
4463 for (FieldSpec &spec : m_fields) {
4471 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4473 for (FieldSpec &spec : m_fields) {
4481 * get label of element by id
4482 * @param id of element
4483 * @return label string or empty string
4485 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4487 for (FieldSpec &spec : m_fields) {
4494 StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
4495 const std::string &name, const std::string &parent_type) {
4498 if (!parent_type.empty()) {
4499 auto it = theme_by_type.find(parent_type);
4500 if (it != theme_by_type.end()) {
4505 auto it = theme_by_type.find(type);
4506 if (it != theme_by_type.end()) {
4510 it = theme_by_name.find(name);
4511 if (it != theme_by_name.end()) {