]> git.lizzy.rs Git - minetest.git/blobdiff - src/gui/guiFormSpecMenu.cpp
8x block meshes (#13133)
[minetest.git] / src / gui / guiFormSpecMenu.cpp
index 9dacf37d7de2dea2378022a44bda01c9f9785a54..68222b319def52a913c0350da1302550494a7086 100644 (file)
@@ -19,24 +19,23 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 
 
 #include <cstdlib>
+#include <cmath>
 #include <algorithm>
 #include <iterator>
-#include <sstream>
 #include <limits>
-#include "guiButton.h"
+#include <sstream>
 #include "guiFormSpecMenu.h"
-#include "guiTable.h"
 #include "constants.h"
 #include "gamedef.h"
 #include "client/keycode.h"
 #include "util/strfnd.h"
+#include <IGUIButton.h>
 #include <IGUICheckBox.h>
+#include <IGUIComboBox.h>
 #include <IGUIEditBox.h>
-#include <IGUIButton.h>
 #include <IGUIStaticText.h>
 #include <IGUIFont.h>
 #include <IGUITabControl.h>
-#include <IGUIComboBox.h>
 #include "client/renderingengine.h"
 #include "log.h"
 #include "client/tile.h" // ITextureSource
@@ -50,17 +49,28 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "settings.h"
 #include "client/client.h"
 #include "client/fontengine.h"
+#include "client/sound.h"
 #include "util/hex.h"
 #include "util/numeric.h"
 #include "util/string.h" // for parseColorString()
 #include "irrlicht_changes/static_text.h"
 #include "client/guiscalingfilter.h"
+#include "guiAnimatedImage.h"
+#include "guiBackgroundImage.h"
+#include "guiBox.h"
+#include "guiButton.h"
+#include "guiButtonImage.h"
+#include "guiButtonItemImage.h"
 #include "guiEditBoxWithScrollbar.h"
-#include "intlGUIEditBox.h"
+#include "guiInventoryList.h"
+#include "guiItemImage.h"
+#include "guiScrollContainer.h"
+#include "guiHyperText.h"
+#include "guiScene.h"
 
 #define MY_CHECKPOS(a,b)                                                                                                       \
        if (v_pos.size() != 2) {                                                                                                \
-               errorstream<< "Invalid pos for element " << a << "specified: \""        \
+               errorstream<< "Invalid pos for element " << a << " specified: \""       \
                        << parts[b] << "\"" << std::endl;                                                               \
                        return;                                                                                                                 \
        }
@@ -68,9 +78,16 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #define MY_CHECKGEOM(a,b)                                                                                                      \
        if (v_geom.size() != 2) {                                                                                               \
                errorstream<< "Invalid geometry for element " << a <<                           \
-                       "specified: \"" << parts[b] << "\"" << std::endl;                               \
+                       " specified: \"" << parts[b] << "\"" << std::endl;                              \
                        return;                                                                                                                 \
        }
+
+#define MY_CHECKCLIENT(a) \
+       if (!m_client) { \
+               errorstream << "Attempted to use element " << a << " with m_client == nullptr." << std::endl; \
+               return; \
+       }
+
 /*
        GUIFormSpecMenu
 */
@@ -86,41 +103,31 @@ inline u32 clamp_u8(s32 value)
 
 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
                gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
-               Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
-               const std::string &formspecPrepend,
-               bool remap_dbl_click):
-       GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
+               Client *client, gui::IGUIEnvironment *guienv, ISimpleTextureSource *tsrc,
+               ISoundManager *sound_manager, IFormSource *fsrc, TextDest *tdst,
+               const std::string &formspecPrepend, bool remap_dbl_click):
+       GUIModalMenu(guienv, parent, id, menumgr, remap_dbl_click),
        m_invmgr(client),
        m_tsrc(tsrc),
+       m_sound_manager(sound_manager),
        m_client(client),
        m_formspec_prepend(formspecPrepend),
        m_form_src(fsrc),
        m_text_dst(tdst),
-       m_joystick(joystick),
-       m_remap_dbl_click(remap_dbl_click)
+       m_joystick(joystick)
 {
        current_keys_pending.key_down = false;
        current_keys_pending.key_up = false;
        current_keys_pending.key_enter = false;
        current_keys_pending.key_escape = false;
 
-       m_doubleclickdetect[0].time = 0;
-       m_doubleclickdetect[1].time = 0;
-
-       m_doubleclickdetect[0].pos = v2s32(0, 0);
-       m_doubleclickdetect[1].pos = v2s32(0, 0);
-
        m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
        m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
 }
 
 GUIFormSpecMenu::~GUIFormSpecMenu()
 {
-       removeChildren();
-
-       for (auto &table_it : m_tables) {
-               table_it.second->drop();
-       }
+       removeAll();
 
        delete m_selected_item;
        delete m_form_src;
@@ -128,12 +135,13 @@ GUIFormSpecMenu::~GUIFormSpecMenu()
 }
 
 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
-       JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
-       const std::string &formspecPrepend)
+       gui::IGUIEnvironment *guienv, JoystickController *joystick, IFormSource *fs_src,
+       TextDest *txt_dest, const std::string &formspecPrepend, ISoundManager *sound_manager)
 {
        if (cur_formspec == nullptr) {
                cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
-                       client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
+                       client, guienv, client->getTextureSource(), sound_manager, fs_src,
+                       txt_dest, formspecPrepend);
                cur_formspec->doPause = false;
 
                /*
@@ -151,20 +159,13 @@ void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
        }
 }
 
-void GUIFormSpecMenu::removeChildren()
+void GUIFormSpecMenu::removeTooltip()
 {
-       const core::list<gui::IGUIElement*> &children = getChildren();
-
-       while(!children.empty()) {
-               (*children.getLast())->remove();
-       }
-
-       if(m_tooltip_element) {
+       if (m_tooltip_element) {
                m_tooltip_element->remove();
                m_tooltip_element->drop();
-               m_tooltip_element = NULL;
+               m_tooltip_element = nullptr;
        }
-
 }
 
 void GUIFormSpecMenu::setInitialFocus()
@@ -177,16 +178,7 @@ void GUIFormSpecMenu::setInitialFocus()
        // 5. first focusable (not statictext, not tabheader)
        // 6. first child element
 
-       core::list<gui::IGUIElement*> children = getChildren();
-
-       // in case "children" contains any NULL elements, remove them
-       for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
-                       it != children.end();) {
-               if (*it)
-                       ++it;
-               else
-                       it = children.erase(it);
-       }
+       const auto& children = getChildren();
 
        // 1. first empty editbox
        for (gui::IGUIElement *it : children) {
@@ -214,8 +206,7 @@ void GUIFormSpecMenu::setInitialFocus()
        }
 
        // 4. last button
-       for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
-                       it != children.end(); --it) {
+       for (auto it = children.rbegin(); it != children.rend(); ++it) {
                if ((*it)->getType() == gui::EGUIET_BUTTON) {
                        Environment->setFocus(*it);
                        return;
@@ -235,7 +226,7 @@ void GUIFormSpecMenu::setInitialFocus()
        if (children.empty())
                Environment->setFocus(this);
        else
-               Environment->setFocus(*(children.begin()));
+               Environment->setFocus(children.front());
 }
 
 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
@@ -256,14 +247,9 @@ std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &
        return NULL;
 }
 
-v2s32 GUIFormSpecMenu::getElementBasePos(bool absolute,
-               const std::vector<std::string> *v_pos)
+v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
 {
-       v2s32 pos = padding;
-       if (absolute)
-               pos += AbsoluteRect.UpperLeftCorner;
-
-       v2f32 pos_f = v2f32(pos.X, pos.Y) + pos_offset * spacing;
+       v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
        if (v_pos) {
                pos_f.X += stof((*v_pos)[0]) * spacing.X;
                pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
@@ -271,18 +257,10 @@ v2s32 GUIFormSpecMenu::getElementBasePos(bool absolute,
        return v2s32(pos_f.X, pos_f.Y);
 }
 
-v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(bool absolute,
-               const std::vector<std::string> &v_pos)
+v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
 {
-       v2f32 pos_f = v2f32(0.0f, 0.0f);
-
-       pos_f.X += stof(v_pos[0]) + pos_offset.X;
-       pos_f.Y += stof(v_pos[1]) + pos_offset.Y;
-
-       if (absolute)
-               return v2s32(pos_f.X * imgsize.X + AbsoluteRect.UpperLeftCorner.X,
-                               pos_f.Y * imgsize.Y + AbsoluteRect.UpperLeftCorner.Y);
-       return v2s32(pos_f.X * imgsize.X, pos_f.Y * imgsize.Y);
+       return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
+               (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
 }
 
 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
@@ -290,8 +268,20 @@ v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string>
        return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
 }
 
+bool GUIFormSpecMenu::precheckElement(const std::string &name, const std::string &element,
+       size_t args_min, size_t args_max, std::vector<std::string> &parts)
+{
+       parts = split(element, ';');
+       if (parts.size() >= args_min && (parts.size() <= args_max || m_formspec_version > FORMSPEC_API_VERSION))
+               return true;
+
+       errorstream << "Invalid " << name << " element(" << parts.size() << "): '" << element << "'" << std::endl;
+       return false;
+}
+
 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
 {
+       // Note: do not use precheckElement due to "," separator.
        std::vector<std::string> parts = split(element,',');
 
        if (((parts.size() == 2) || parts.size() == 3) ||
@@ -304,7 +294,7 @@ void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
                data->invsize.Y = MYMAX(0, stof(parts[1]));
 
                lockSize(false);
-#ifndef __ANDROID__
+#ifndef HAVE_TOUCHSCREENGUI
                if (parts.size() == 3) {
                        if (parts[2] == "true") {
                                lockSize(true,v2u32(800,600));
@@ -343,71 +333,189 @@ void GUIFormSpecMenu::parseContainerEnd(parserData* data)
        }
 }
 
-void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
 {
-       if (m_client == 0) {
-               warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
+       std::vector<std::string> parts;
+       if (!precheckElement("scroll_container start", element, 4, 5, parts))
                return;
-       }
 
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> v_pos  = split(parts[0], ',');
+       std::vector<std::string> v_geom = split(parts[1], ',');
+       std::string scrollbar_name = parts[2];
+       std::string orientation = parts[3];
+       f32 scroll_factor = 0.1f;
+       if (parts.size() >= 5 && !parts[4].empty())
+               scroll_factor = stof(parts[4]);
 
-       if (((parts.size() == 4) || (parts.size() == 5)) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::string location = parts[0];
-               std::string listname = parts[1];
-               std::vector<std::string> v_pos  = split(parts[2],',');
-               std::vector<std::string> v_geom = split(parts[3],',');
-               std::string startindex;
-               if (parts.size() == 5)
-                       startindex = parts[4];
+       MY_CHECKPOS("scroll_container", 0);
+       MY_CHECKGEOM("scroll_container", 1);
 
-               MY_CHECKPOS("list",2);
-               MY_CHECKGEOM("list",3);
+       v2s32 pos = getRealCoordinateBasePos(v_pos);
+       v2s32 geom = getRealCoordinateGeometry(v_geom);
 
-               InventoryLocation loc;
+       if (orientation == "vertical")
+               scroll_factor *= -imgsize.Y;
+       else if (orientation == "horizontal")
+               scroll_factor *= -imgsize.X;
+       else
+               warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
+                               << "Invalid scroll_container orientation: " << orientation
+                               << std::endl;
+
+       // old parent (at first: this)
+       // ^ is parent of clipper
+       // ^ is parent of mover
+       // ^ is parent of other elements
+
+       // make clipper
+       core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
+
+       gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
+                       data->current_parent, 0, rect_clipper);
+
+       // make mover
+       FieldSpec spec_mover(
+               "",
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
 
-               if (location == "context" || location == "current_name")
-                       loc = m_current_inventory_location;
-               else
-                       loc.deSerialize(location);
+       core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
 
-               v2s32 pos;
-               v2s32 geom;
+       GUIScrollContainer *mover = new GUIScrollContainer(Environment,
+                       clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
 
-               if (data->real_coordinates)
-                       pos = getRealCoordinateBasePos(true, v_pos);
-               else
-                       pos = getElementBasePos(true, &v_pos);
+       data->current_parent = mover;
 
-               geom.X = stoi(v_geom[0]);
-               geom.Y = stoi(v_geom[1]);
+       m_scroll_containers.emplace_back(scrollbar_name, mover);
 
-               s32 start_i = 0;
-               if (!startindex.empty())
-                       start_i = stoi(startindex);
+       m_fields.push_back(spec_mover);
 
-               if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
-                       errorstream<< "Invalid list element: '" << element << "'"  << std::endl;
-                       return;
-               }
+       clipper->drop();
+
+       // remove interferring offset of normal containers
+       container_stack.push(pos_offset);
+       pos_offset.X = 0.0f;
+       pos_offset.Y = 0.0f;
+}
+
+void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
+{
+       if (data->current_parent == this || data->current_parent->getParent() == this ||
+                       container_stack.empty()) {
+               errorstream << "Invalid scroll_container end element, "
+                               << "no matching scroll_container start element" << std::endl;
+               return;
+       }
 
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of list without a size[] element"<<std::endl;
-               m_inventorylists.emplace_back(loc, listname, pos, geom, start_i, data->real_coordinates);
+       if (pos_offset.getLengthSQ() != 0.0f) {
+               // pos_offset is only set by containers and scroll_containers.
+               // scroll_containers always set it to 0,0 which means that if it is
+               // not 0,0, it is a normal container that was opened last, not a
+               // scroll_container
+               errorstream << "Invalid scroll_container end element, "
+                               << "an inner container was left open" << std::endl;
                return;
        }
-       errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       data->current_parent = data->current_parent->getParent()->getParent();
+       pos_offset = container_stack.top();
+       container_stack.pop();
 }
 
-void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
 {
-       if (m_client == 0) {
-               errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
+       MY_CHECKCLIENT("list");
+
+       std::vector<std::string> parts;
+       if (!precheckElement("list", element, 4, 5, parts))
+               return;
+
+       std::string location = parts[0];
+       std::string listname = parts[1];
+       std::vector<std::string> v_pos  = split(parts[2],',');
+       std::vector<std::string> v_geom = split(parts[3],',');
+       std::string startindex;
+       if (parts.size() == 5)
+               startindex = parts[4];
+
+       MY_CHECKPOS("list",2);
+       MY_CHECKGEOM("list",3);
+
+       InventoryLocation loc;
+
+       if (location == "context" || location == "current_name")
+               loc = m_current_inventory_location;
+       else
+               loc.deSerialize(location);
+
+       v2s32 geom;
+       geom.X = stoi(v_geom[0]);
+       geom.Y = stoi(v_geom[1]);
+
+       s32 start_i = 0;
+       if (!startindex.empty())
+               start_i = stoi(startindex);
+
+       if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
+               errorstream << "Invalid list element: '" << element << "'"  << std::endl;
                return;
        }
 
+       if (!data->explicit_size)
+               warningstream << "invalid use of list without a size[] element" << std::endl;
+
+       FieldSpec spec(
+               "",
+               L"",
+               L"",
+               258 + m_fields.size(),
+               3
+       );
+
+       auto style = getDefaultStyleForElement("list", spec.fname);
+
+       v2f32 slot_scale = style.getVector2f(StyleSpec::SIZE, v2f32(0, 0));
+       v2f32 slot_size(
+               slot_scale.X <= 0 ? imgsize.X : std::max<f32>(slot_scale.X * imgsize.X, 1),
+               slot_scale.Y <= 0 ? imgsize.Y : std::max<f32>(slot_scale.Y * imgsize.Y, 1)
+       );
+
+       v2f32 slot_spacing = style.getVector2f(StyleSpec::SPACING, v2f32(-1, -1));
+       v2f32 default_spacing = data->real_coordinates ?
+                       v2f32(imgsize.X * 0.25f, imgsize.Y * 0.25f) :
+                       v2f32(spacing.X - imgsize.X, spacing.Y - imgsize.Y);
+
+       slot_spacing.X = slot_spacing.X < 0 ? default_spacing.X :
+                       imgsize.X * slot_spacing.X;
+       slot_spacing.Y = slot_spacing.Y < 0 ? default_spacing.Y :
+                       imgsize.Y * slot_spacing.Y;
+
+       slot_spacing += slot_size;
+
+       v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) :
+                       getElementBasePos(&v_pos);
+
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
+                       pos.X + (geom.X - 1) * slot_spacing.X + slot_size.X,
+                       pos.Y + (geom.Y - 1) * slot_spacing.Y + slot_size.Y);
+
+       GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
+                       spec.fid, rect, m_invmgr, loc, listname, geom, start_i,
+                       v2s32(slot_size.X, slot_size.Y), slot_spacing, this,
+                       data->inventorylist_options, m_font);
+
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+
+       m_inventorylists.push_back(e);
+       m_fields.push_back(spec);
+}
+
+void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
+{
+       MY_CHECKCLIENT("listring");
+
        std::vector<std::string> parts = split(element, ';');
 
        if (parts.size() == 2) {
@@ -428,10 +536,10 @@ void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element
        if (element.empty() && m_inventorylists.size() > 1) {
                size_t siz = m_inventorylists.size();
                // insert the last two inv list elements into the list ring
-               const ListDrawSpec &spa = m_inventorylists[siz - 2];
-               const ListDrawSpec &spb = m_inventorylists[siz - 1];
-               m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname);
-               m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname);
+               const GUIInventoryList *spa = m_inventorylists[siz - 2];
+               const GUIInventoryList *spb = m_inventorylists[siz - 1];
+               m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname());
+               m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname());
                return;
        }
 
@@ -441,382 +549,576 @@ void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element
 
 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
-
-       if (((parts.size() >= 3) && (parts.size() <= 4)) ||
-               ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::string name = parts[1];
-               std::string label = parts[2];
-               std::string selected;
+       std::vector<std::string> parts;
+       if (!precheckElement("checkbox", element, 3, 4, parts))
+               return;
 
-               if (parts.size() >= 4)
-                       selected = parts[3];
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::string name = parts[1];
+       std::string label = parts[2];
+       std::string selected;
 
-               MY_CHECKPOS("checkbox",0);
+       if (parts.size() >= 4)
+               selected = parts[3];
 
-               bool fselected = false;
+       MY_CHECKPOS("checkbox",0);
 
-               if (selected == "true")
-                       fselected = true;
+       bool fselected = false;
 
-               std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
-               const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
-               s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
-               s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
+       if (selected == "true")
+               fselected = true;
 
-               v2s32 pos;
-               core::rect<s32> rect;
+       std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
+       const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
+       s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
+       s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
+       v2s32 pos;
+       core::rect<s32> rect;
 
-                       rect = core::rect<s32>(
-                                       pos.X,
-                                       pos.Y - y_center,
-                                       pos.X + label_size.Width + cb_size + 7,
-                                       pos.Y + y_center
-                               );
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       rect = core::rect<s32>(
-                                       pos.X,
-                                       pos.Y + imgsize.Y / 2 - y_center,
-                                       pos.X + label_size.Width + cb_size + 7,
-                                       pos.Y + imgsize.Y / 2 + y_center
-                               );
-               }
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
 
-               FieldSpec spec(
-                               name,
-                               wlabel, //Needed for displaying text on MSVC
-                               wlabel,
-                               258+m_fields.size()
+               rect = core::rect<s32>(
+                               pos.X,
+                               pos.Y - y_center,
+                               pos.X + label_size.Width + cb_size + 7,
+                               pos.Y + y_center
                        );
+       } else {
+               pos = getElementBasePos(&v_pos);
+               rect = core::rect<s32>(
+                               pos.X,
+                               pos.Y + imgsize.Y / 2 - y_center,
+                               pos.X + label_size.Width + cb_size + 7,
+                               pos.Y + imgsize.Y / 2 + y_center
+                       );
+       }
+
+       FieldSpec spec(
+                       name,
+                       wlabel, //Needed for displaying text on MSVC
+                       wlabel,
+                       258+m_fields.size()
+               );
 
-               spec.ftype = f_CheckBox;
+       spec.ftype = f_CheckBox;
 
-               gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this,
-                                       spec.fid, spec.flabel.c_str());
+       gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
+                       data->current_parent, spec.fid, spec.flabel.c_str());
 
-               auto style = getStyleForElement("checkbox", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       auto style = getDefaultStyleForElement("checkbox", name);
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       spec.sound = style.get(StyleSpec::Property::SOUND, "");
 
-               m_checkboxes.emplace_back(spec,e);
-               m_fields.push_back(spec);
-               return;
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
        }
-       errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       e->grab();
+       m_checkboxes.emplace_back(spec, e);
+       m_fields.push_back(spec);
 }
 
 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
-
-       if (parts.size() >= 5) {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[3];
-               std::string value = parts[4];
+       std::vector<std::string> parts;
+       if (!precheckElement("scrollbar", element, 5, 5, parts))
+               return;
 
-               MY_CHECKPOS("scrollbar",0);
-               MY_CHECKGEOM("scrollbar",1);
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[3];
+       std::string value = parts[4];
 
-               v2s32 pos;
-               v2s32 dim;
+       MY_CHECKPOS("scrollbar",0);
+       MY_CHECKGEOM("scrollbar",1);
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       dim = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       dim.X = stof(v_geom[0]) * spacing.X;
-                       dim.Y = stof(v_geom[1]) * spacing.Y;
-               }
+       v2s32 pos;
+       v2s32 dim;
 
-               core::rect<s32> rect =
-                               core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               dim = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               dim.X = stof(v_geom[0]) * spacing.X;
+               dim.Y = stof(v_geom[1]) * spacing.Y;
+       }
 
-               FieldSpec spec(
-                               name,
-                               L"",
-                               L"",
-                               258+m_fields.size()
-                       );
+       core::rect<s32> rect =
+                       core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
 
-               bool is_horizontal = true;
+       FieldSpec spec(
+                       name,
+                       L"",
+                       L"",
+                       258+m_fields.size()
+               );
 
-               if (parts[2] == "vertical")
-                       is_horizontal = false;
+       bool is_horizontal = true;
 
-               spec.ftype = f_ScrollBar;
-               spec.send  = true;
-               gui::IGUIScrollBar* e =
-                               Environment->addScrollBar(is_horizontal,rect,this,spec.fid);
+       if (parts[2] == "vertical")
+               is_horizontal = false;
 
-               auto style = getStyleForElement("scrollbar", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       spec.ftype = f_ScrollBar;
+       spec.send  = true;
+       GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent,
+                       spec.fid, rect, is_horizontal, true);
 
-               e->setMax(1000);
-               e->setMin(0);
-               e->setPos(stoi(parts[4]));
-               e->setSmallStep(10);
-               e->setLargeStep(100);
+       auto style = getDefaultStyleForElement("scrollbar", name);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
 
-               m_scrollbars.emplace_back(spec,e);
-               m_fields.push_back(spec);
-               return;
-       }
-       errorstream<< "Invalid scrollbar element(" << parts.size() << "): '" << element << "'"  << std::endl;
-}
+       s32 max = data->scrollbar_options.max;
+       s32 min = data->scrollbar_options.min;
 
-void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
-{
-       std::vector<std::string> parts = split(element,';');
+       e->setMax(max);
+       e->setMin(min);
 
-       if ((parts.size() == 3) ||
-               ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = unescape_string(parts[2]);
+       e->setPos(stoi(value));
 
-               MY_CHECKPOS("image", 0);
-               MY_CHECKGEOM("image", 1);
+       e->setSmallStep(data->scrollbar_options.small_step);
+       e->setLargeStep(data->scrollbar_options.large_step);
 
-               v2s32 pos;
-               v2s32 geom;
+       s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(true, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(true, &v_pos);
-                       geom.X = stof(v_geom[0]) * (float)imgsize.X;
-                       geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
-               }
+       e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
 
-               if (!data->explicit_size)
-                       warningstream<<"invalid use of image without a size[] element"<<std::endl;
-               m_images.emplace_back(name, pos, geom);
-               return;
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
        }
 
-       if (parts.size() == 2) {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::string name = unescape_string(parts[1]);
-
-               MY_CHECKPOS("image", 0);
-
-               v2s32 pos = getElementBasePos(true, &v_pos);
-
-               if (!data->explicit_size)
-                       warningstream<<"invalid use of image without a size[] element"<<std::endl;
-               m_images.emplace_back(name, pos);
-               return;
-       }
-       errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       m_scrollbars.emplace_back(spec,e);
+       m_fields.push_back(spec);
 }
 
-void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts = split(element, ';');
 
-       if ((parts.size() == 3) ||
-               ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[2];
+       if (parts.size() == 0) {
+               warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
+                       element << "'"  << std::endl;
+               return;
+       }
 
-               MY_CHECKPOS("itemimage",0);
-               MY_CHECKGEOM("itemimage",1);
+       for (const std::string &i : parts) {
+               std::vector<std::string> options = split(i, '=');
 
-               v2s32 pos;
-               v2s32 geom;
+               if (options.size() != 2) {
+                       warningstream << "Invalid scrollbaroptions option syntax: '" <<
+                               element << "'" << std::endl;
+                       continue; // Go to next option
+               }
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(true, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(true, &v_pos);
-                       geom.X = stof(v_geom[0]) * (float)imgsize.X;
-                       geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
+               if (options[0] == "max") {
+                       data->scrollbar_options.max = stoi(options[1]);
+                       continue;
+               } else if (options[0] == "min") {
+                       data->scrollbar_options.min = stoi(options[1]);
+                       continue;
+               } else if (options[0] == "smallstep") {
+                       int value = stoi(options[1]);
+                       data->scrollbar_options.small_step = value < 0 ? 10 : value;
+                       continue;
+               } else if (options[0] == "largestep") {
+                       int value = stoi(options[1]);
+                       data->scrollbar_options.large_step = value < 0 ? 100 : value;
+                       continue;
+               } else if (options[0] == "thumbsize") {
+                       int value = stoi(options[1]);
+                       data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
+                       continue;
+               } else if (options[0] == "arrows") {
+                       std::string value = trim(options[1]);
+                       if (value == "hide")
+                               data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
+                       else if (value == "show")
+                               data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
+                       else // Auto hide/show
+                               data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
+                       continue;
                }
 
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
-               m_itemimages.emplace_back("", name, pos, geom);
-               return;
+               warningstream << "Invalid scrollbaroptions option(" << options[0] <<
+                       "): '" << element << "'" << std::endl;
        }
-       errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
 }
 
-void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
-               const std::string &type)
+void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("image", element, 2, 4, parts))
+               return;
 
-       if ((parts.size() == 4) ||
-               ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[2];
-               std::string label = parts[3];
+       size_t offset = parts.size() >= 3;
 
-               MY_CHECKPOS("button",0);
-               MY_CHECKGEOM("button",1);
+       std::vector<std::string> v_pos = split(parts[0],',');
+       MY_CHECKPOS("image", 0);
 
-               v2s32 pos;
-               v2s32 geom;
-               core::rect<s32> rect;
+       std::vector<std::string> v_geom;
+       if (parts.size() >= 3) {
+               v_geom = split(parts[1],',');
+               MY_CHECKGEOM("image", 1);
+       }
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-                       rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
-                               pos.Y+geom.Y);
+       std::string name = unescape_string(parts[1 + offset]);
+       video::ITexture *texture = m_tsrc->getTexture(name);
+
+       v2s32 pos;
+       v2s32 geom;
+
+       if (parts.size() < 3) {
+               if (texture != nullptr) {
+                       core::dimension2du dim = texture->getOriginalSize();
+                       geom.X = dim.Width;
+                       geom.Y = dim.Height;
                } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
-                       pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
+                       geom = v2s32(0);
+               }
+       }
 
-                       rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
-                                               pos.X + geom.X, pos.Y + m_btn_height);
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               if (parts.size() >= 3)
+                       geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               if (parts.size() >= 3) {
+                       geom.X = stof(v_geom[0]) * (float)imgsize.X;
+                       geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
                }
+       }
 
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of button without a size[] element"<<std::endl;
+       if (!data->explicit_size)
+               warningstream << "Invalid use of image without a size[] element" << std::endl;
 
-               std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size(),
+               1
+       );
 
-               FieldSpec spec(
-                       name,
-                       wlabel,
-                       L"",
-                       258+m_fields.size()
-               );
-               spec.ftype = f_Button;
-               if(type == "button_exit")
-                       spec.is_exit = true;
+       core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
 
-               GUIButton *e = GUIButton::addButton(Environment, rect, this, spec.fid, spec.flabel.c_str());
+       core::rect<s32> middle;
+       if (parts.size() >= 4)
+               parseMiddleRect(parts[3], &middle);
 
-               auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
-               if (style.isNotDefault(StyleSpec::BGCOLOR)) {
-                       e->setColor(style.getColor(StyleSpec::BGCOLOR));
-               }
-               if (style.isNotDefault(StyleSpec::TEXTCOLOR)) {
-                       e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR));
-               }
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-               e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
+       // Temporary fix for issue #12581 in 5.6.0.
+       // Use legacy image when not rendering 9-slice image because GUIAnimatedImage
+       // uses NNAA filter which causes visual artifacts when image uses alpha blending.
 
-               if (style.isNotDefault(StyleSpec::BGIMG)) {
-                       std::string image_name = style.get(StyleSpec::BGIMG, "");
-                       std::string pressed_image_name = style.get(StyleSpec::BGIMG_PRESSED, "");
+       gui::IGUIElement *e;
+       if (middle.getArea() > 0) {
+               GUIAnimatedImage *image = new GUIAnimatedImage(Environment, data->current_parent,
+                       spec.fid, rect);
 
-                       video::ITexture *texture = 0;
-                       video::ITexture *pressed_texture = 0;
-                       texture = m_tsrc->getTexture(image_name);
-                       if (!pressed_image_name.empty())
-                               pressed_texture = m_tsrc->getTexture(pressed_image_name);
-                       else
-                               pressed_texture = texture;
-
-                       e->setUseAlphaChannel(style.getBool(StyleSpec::ALPHA, true));
-                       e->setImage(guiScalingImageButton(
-                                       Environment->getVideoDriver(), texture, geom.X, geom.Y));
-                       e->setPressedImage(guiScalingImageButton(
-                                       Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
-                       e->setScaleImage(true);
-               }
+               image->setTexture(texture);
+               image->setMiddleRect(middle);
+               e = image;
+       }
+       else {
+               gui::IGUIImage *image = Environment->addImage(rect, data->current_parent, spec.fid, nullptr, true);
+               image->setImage(texture);
+               image->setScaleImage(true);
+               image->grab(); // compensate for drop in addImage
+               e = image;
+       }
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       auto style = getDefaultStyleForElement("image", spec.fname);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
 
-               m_fields.push_back(spec);
-               return;
-       }
-       errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       // Animated images should let events through
+       m_clickthrough_elements.push_back(e);
+
+       m_fields.push_back(spec);
 }
 
-void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("animated_image", element, 6, 8, parts))
+               return;
 
-       if ((parts.size() >= 3 && parts.size() <= 5) ||
-                       (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = unescape_string(parts[2]);
+       std::vector<std::string> v_pos  = split(parts[0], ',');
+       std::vector<std::string> v_geom = split(parts[1], ',');
+       std::string name = parts[2];
+       std::string texture_name = unescape_string(parts[3]);
+       s32 frame_count = stoi(parts[4]);
+       s32 frame_duration = stoi(parts[5]);
 
-               MY_CHECKPOS("background",0);
-               MY_CHECKGEOM("background",1);
+       MY_CHECKPOS("animated_image", 0);
+       MY_CHECKGEOM("animated_image", 1);
 
-               v2s32 pos;
-               v2s32 geom;
+       v2s32 pos;
+       v2s32 geom;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(true, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(true, &v_pos);
-                       pos.X -= (spacing.X - (float)imgsize.X) / 2;
-                       pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * (float)imgsize.X;
+               geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
+       }
 
-                       geom.X = stof(v_geom[0]) * spacing.X;
-                       geom.Y = stof(v_geom[1]) * spacing.Y;
-               }
+       if (!data->explicit_size)
+               warningstream << "Invalid use of animated_image without a size[] element"
+                               << std::endl;
 
-               bool clip = false;
-               if (parts.size() >= 4 && is_yes(parts[3])) {
-                       if (data->real_coordinates) {
-                               pos = getRealCoordinateBasePos(false, v_pos) * -1;
-                               geom = v2s32(0, 0);
-                       } else {
-                               pos.X = stoi(v_pos[0]); //acts as offset
-                               pos.Y = stoi(v_pos[1]);
-                       }
-                       clip = true;
-               }
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
+       spec.ftype = f_AnimatedImage;
+       spec.send = true;
 
-               core::rect<s32> middle;
-               if (parts.size() >= 5) {
-                       std::vector<std::string> v_middle = split(parts[4], ',');
-                       if (v_middle.size() == 1) {
-                               s32 x = stoi(v_middle[0]);
-                               middle.UpperLeftCorner = core::vector2di(x, x);
-                               middle.LowerRightCorner = core::vector2di(-x, -x);
-                       } else if (v_middle.size() == 2) {
-                               s32 x = stoi(v_middle[0]);
-                               s32 y = stoi(v_middle[1]);
-                               middle.UpperLeftCorner = core::vector2di(x, y);
-                               middle.LowerRightCorner = core::vector2di(-x, -y);
-                               // `-x` is interpreted as `w - x`
-                       } else if (v_middle.size() == 4) {
-                               middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
-                               middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
-                       } else {
-                               warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
-                       }
-               }
+       core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
+
+       core::rect<s32> middle;
+       if (parts.size() >= 8)
+               parseMiddleRect(parts[7], &middle);
+
+       GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent,
+               spec.fid, rect);
+
+       e->setTexture(m_tsrc->getTexture(texture_name));
+       e->setMiddleRect(middle);
+       e->setFrameDuration(frame_duration);
+       e->setFrameCount(frame_count);
+       if (parts.size() >= 7)
+               e->setFrameIndex(stoi(parts[6]) - 1);
+
+       auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+
+       // Animated images should let events through
+       m_clickthrough_elements.push_back(e);
+
+       m_fields.push_back(spec);
+}
+
+void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
+{
+       std::vector<std::string> parts;
+       if (!precheckElement("item_image", element, 3, 3, parts))
+               return;
+
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[2];
+
+       MY_CHECKPOS("item_image",0);
+       MY_CHECKGEOM("item_image",1);
+
+       v2s32 pos;
+       v2s32 geom;
+
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * (float)imgsize.X;
+               geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
+       }
+
+       if(!data->explicit_size)
+               warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
+
+       FieldSpec spec(
+               "",
+               L"",
+               L"",
+               258 + m_fields.size(),
+               2
+       );
+       spec.ftype = f_ItemImage;
+
+       GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
+                       core::rect<s32>(pos, pos + geom), name, m_font, m_client);
+       auto style = getDefaultStyleForElement("item_image", spec.fname);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+
+       // item images should let events through
+       m_clickthrough_elements.push_back(e);
+
+       m_fields.push_back(spec);
+}
+
+void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
+               const std::string &type)
+{
+       std::vector<std::string> parts;
+       if (!precheckElement("button", element, 4, 4, parts))
+               return;
+
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[2];
+       std::string label = parts[3];
+
+       MY_CHECKPOS("button",0);
+       MY_CHECKGEOM("button",1);
+
+       v2s32 pos;
+       v2s32 geom;
+       core::rect<s32> rect;
+
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+               rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
+                       pos.Y+geom.Y);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
+               pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
+
+               rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
+                                       pos.X + geom.X, pos.Y + m_btn_height);
+       }
+
+       if(!data->explicit_size)
+               warningstream<<"invalid use of button without a size[] element"<<std::endl;
+
+       std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
+
+       FieldSpec spec(
+               name,
+               wlabel,
+               L"",
+               258 + m_fields.size()
+       );
+       spec.ftype = f_Button;
+       if(type == "button_exit")
+               spec.is_exit = true;
+
+       GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
+                       data->current_parent, spec.fid, spec.flabel.c_str());
+
+       auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
+
+       spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
 
-               if (!data->explicit_size && !clip)
-                       warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
+       e->setStyles(style);
 
-               m_backgrounds.emplace_back(name, pos, geom, middle, clip);
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
+
+       m_fields.push_back(spec);
+}
+
+bool GUIFormSpecMenu::parseMiddleRect(const std::string &value, core::rect<s32> *parsed_rect)
+{
+       core::rect<s32> rect;
+       std::vector<std::string> v_rect = split(value, ',');
+
+       if (v_rect.size() == 1) {
+               s32 x = stoi(v_rect[0]);
+               rect.UpperLeftCorner = core::vector2di(x, x);
+               rect.LowerRightCorner = core::vector2di(-x, -x);
+       } else if (v_rect.size() == 2) {
+               s32 x = stoi(v_rect[0]);
+               s32 y = stoi(v_rect[1]);
+               rect.UpperLeftCorner = core::vector2di(x, y);
+               rect.LowerRightCorner = core::vector2di(-x, -y);
+               // `-x` is interpreted as `w - x`
+       } else if (v_rect.size() == 4) {
+               rect.UpperLeftCorner = core::vector2di(stoi(v_rect[0]), stoi(v_rect[1]));
+               rect.LowerRightCorner = core::vector2di(stoi(v_rect[2]), stoi(v_rect[3]));
+       } else {
+               warningstream << "Invalid rectangle string format: \"" << value
+                               << "\"" << std::endl;
+               return false;
+       }
+
+       *parsed_rect = rect;
+
+       return true;
+}
 
+void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
+{
+       std::vector<std::string> parts;
+       if (!precheckElement("background", element, 3, 5, parts))
                return;
+
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = unescape_string(parts[2]);
+
+       MY_CHECKPOS("background",0);
+       MY_CHECKGEOM("background",1);
+
+       v2s32 pos;
+       v2s32 geom;
+
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               pos.X -= (spacing.X - (float)imgsize.X) / 2;
+               pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
+
+               geom.X = stof(v_geom[0]) * spacing.X;
+               geom.Y = stof(v_geom[1]) * spacing.Y;
        }
-       errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       bool clip = false;
+       if (parts.size() >= 4 && is_yes(parts[3])) {
+               if (data->real_coordinates) {
+                       pos = getRealCoordinateBasePos(v_pos) * -1;
+                       geom = v2s32(0, 0);
+               } else {
+                       pos.X = stoi(v_pos[0]); //acts as offset
+                       pos.Y = stoi(v_pos[1]);
+               }
+               clip = true;
+       }
+
+       core::rect<s32> middle;
+       if (parts.size() >= 5)
+               parseMiddleRect(parts[4], &middle);
+
+       if (!data->explicit_size && !clip)
+               warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
+
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
+
+       core::rect<s32> rect;
+       if (!clip) {
+               // no auto_clip => position like normal image
+               rect = core::rect<s32>(pos, pos + geom);
+       } else {
+               // it will be auto-clipped when drawing
+               rect = core::rect<s32>(-pos, pos);
+       }
+
+       GUIBackgroundImage *e = new GUIBackgroundImage(Environment, data->background_parent.get(),
+                       spec.fid, rect, name, middle, m_tsrc, clip);
+
+       FATAL_ERROR_IF(!e, "Failed to create background formspec element");
+
+       e->setNotClipped(true);
+
+       m_fields.push_back(spec);
+       e->drop();
 }
 
 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
@@ -853,331 +1155,319 @@ void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &ele
 
 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("table", element, 4, 5, parts))
+               return;
 
-       if (((parts.size() == 4) || (parts.size() == 5)) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[2];
-               std::vector<std::string> items = split(parts[3],',');
-               std::string str_initial_selection;
-               std::string str_transparent = "false";
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[2];
+       std::vector<std::string> items = split(parts[3],',');
+       std::string str_initial_selection;
 
-               if (parts.size() >= 5)
-                       str_initial_selection = parts[4];
+       if (parts.size() >= 5)
+               str_initial_selection = parts[4];
 
-               MY_CHECKPOS("table",0);
-               MY_CHECKGEOM("table",1);
+       MY_CHECKPOS("table",0);
+       MY_CHECKGEOM("table",1);
 
-               v2s32 pos;
-               v2s32 geom;
+       v2s32 pos;
+       v2s32 geom;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       geom.X = stof(v_geom[0]) * spacing.X;
-                       geom.Y = stof(v_geom[1]) * spacing.Y;
-               }
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * spacing.X;
+               geom.Y = stof(v_geom[1]) * spacing.Y;
+       }
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
 
-               FieldSpec spec(
-                       name,
-                       L"",
-                       L"",
-                       258+m_fields.size()
-               );
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
 
-               spec.ftype = f_Table;
+       spec.ftype = f_Table;
 
-               for (std::string &item : items) {
-                       item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
-               }
+       for (std::string &item : items) {
+               item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
+       }
 
-               //now really show table
-               GUITable *e = new GUITable(Environment, this, spec.fid, rect,
-                               m_tsrc);
+       //now really show table
+       GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
+                       rect, m_tsrc);
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
 
-               e->setTable(data->table_options, data->table_columns, items);
+       e->setTable(data->table_options, data->table_columns, items);
 
-               if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
-                       e->setDynamicData(data->table_dyndata[name]);
-               }
+       if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
+               e->setDynamicData(data->table_dyndata[name]);
+       }
 
-               if (!str_initial_selection.empty() && str_initial_selection != "0")
-                       e->setSelected(stoi(str_initial_selection));
+       if (!str_initial_selection.empty() && str_initial_selection != "0")
+               e->setSelected(stoi(str_initial_selection));
 
-               auto style = getStyleForElement("table", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       auto style = getDefaultStyleForElement("table", name);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       e->setOverrideFont(style.getFont());
 
-               m_tables.emplace_back(spec, e);
-               m_fields.push_back(spec);
-               return;
-       }
-       errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       m_tables.emplace_back(spec, e);
+       m_fields.push_back(spec);
 }
 
 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("textlist", element, 4, 6, parts))
+               return;
 
-       if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
-               ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[2];
-               std::vector<std::string> items = split(parts[3],',');
-               std::string str_initial_selection;
-               std::string str_transparent = "false";
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[2];
+       std::vector<std::string> items = split(parts[3],',');
+       std::string str_initial_selection;
+       std::string str_transparent = "false";
 
-               if (parts.size() >= 5)
-                       str_initial_selection = parts[4];
+       if (parts.size() >= 5)
+               str_initial_selection = parts[4];
 
-               if (parts.size() >= 6)
-                       str_transparent = parts[5];
+       if (parts.size() >= 6)
+               str_transparent = parts[5];
 
-               MY_CHECKPOS("textlist",0);
-               MY_CHECKGEOM("textlist",1);
+       MY_CHECKPOS("textlist",0);
+       MY_CHECKGEOM("textlist",1);
 
-               v2s32 pos;
-               v2s32 geom;
+       v2s32 pos;
+       v2s32 geom;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       geom.X = stof(v_geom[0]) * spacing.X;
-                       geom.Y = stof(v_geom[1]) * spacing.Y;
-               }
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * spacing.X;
+               geom.Y = stof(v_geom[1]) * spacing.Y;
+       }
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
 
-               FieldSpec spec(
-                       name,
-                       L"",
-                       L"",
-                       258+m_fields.size()
-               );
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
 
-               spec.ftype = f_Table;
+       spec.ftype = f_Table;
 
-               for (std::string &item : items) {
-                       item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
-               }
+       for (std::string &item : items) {
+               item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
+       }
 
-               //now really show list
-               GUITable *e = new GUITable(Environment, this, spec.fid, rect,
-                               m_tsrc);
+       //now really show list
+       GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
+                       rect, m_tsrc);
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
 
-               e->setTextList(items, is_yes(str_transparent));
+       e->setTextList(items, is_yes(str_transparent));
 
-               if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
-                       e->setDynamicData(data->table_dyndata[name]);
-               }
+       if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
+               e->setDynamicData(data->table_dyndata[name]);
+       }
 
-               if (!str_initial_selection.empty() && str_initial_selection != "0")
-                       e->setSelected(stoi(str_initial_selection));
+       if (!str_initial_selection.empty() && str_initial_selection != "0")
+               e->setSelected(stoi(str_initial_selection));
 
-               auto style = getStyleForElement("textlist", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       auto style = getDefaultStyleForElement("textlist", name);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       e->setOverrideFont(style.getFont());
 
-               m_tables.emplace_back(spec, e);
-               m_fields.push_back(spec);
-               return;
-       }
-       errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       m_tables.emplace_back(spec, e);
+       m_fields.push_back(spec);
 }
 
-
 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("dropdown", element, 5, 6, parts))
+               return;
 
-       if ((parts.size() == 5) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::string name = parts[2];
-               std::vector<std::string> items = split(parts[3],',');
-               std::string str_initial_selection;
-               str_initial_selection = parts[4];
+       std::vector<std::string> v_pos = split(parts[0], ',');
+       std::string name = parts[2];
+       std::vector<std::string> items = split(parts[3], ',');
+       std::string str_initial_selection = parts[4];
 
-               MY_CHECKPOS("dropdown",0);
+       if (parts.size() >= 6 && is_yes(parts[5]))
+               m_dropdown_index_event[name] = true;
 
-               v2s32 pos;
-               v2s32 geom;
-               core::rect<s32> rect;
+       MY_CHECKPOS("dropdown",0);
 
-               if (data->real_coordinates) {
-                       std::vector<std::string> v_geom = split(parts[1],',');
+       v2s32 pos;
+       v2s32 geom;
+       core::rect<s32> rect;
 
-                       if (v_geom.size() == 1)
-                               v_geom.emplace_back("1");
+       if (data->real_coordinates) {
+               std::vector<std::string> v_geom = split(parts[1],',');
 
-                       MY_CHECKGEOM("dropdown",1);
+               if (v_geom.size() == 1)
+                       v_geom.emplace_back("1");
 
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-                       rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
+               MY_CHECKGEOM("dropdown",1);
 
-                       s32 width = stof(parts[1]) * spacing.Y;
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+               rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
+       } else {
+               pos = getElementBasePos(&v_pos);
 
-                       rect = core::rect<s32>(pos.X, pos.Y,
-                                       pos.X + width, pos.Y + (m_btn_height * 2));
-               }
+               s32 width = stof(parts[1]) * spacing.Y;
 
-               FieldSpec spec(
-                       name,
-                       L"",
-                       L"",
-                       258+m_fields.size()
-               );
+               rect = core::rect<s32>(pos.X, pos.Y,
+                               pos.X + width, pos.Y + (m_btn_height * 2));
+       }
 
-               spec.ftype = f_DropDown;
-               spec.send = true;
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
 
-               //now really show list
-               gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
+       spec.ftype = f_DropDown;
+       spec.send = true;
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       //now really show list
+       gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
+                       spec.fid);
 
-               for (const std::string &item : items) {
-                       e->addItem(unescape_translate(unescape_string(
-                               utf8_to_wide(item))).c_str());
-               }
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
 
-               if (!str_initial_selection.empty())
-                       e->setSelected(stoi(str_initial_selection)-1);
+       for (const std::string &item : items) {
+               e->addItem(unescape_translate(unescape_string(
+                       utf8_to_wide(item))).c_str());
+       }
 
-               auto style = getStyleForElement("dropdown", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       if (!str_initial_selection.empty())
+               e->setSelected(stoi(str_initial_selection)-1);
 
-               m_fields.push_back(spec);
+       auto style = getDefaultStyleForElement("dropdown", name);
 
-               m_dropdowns.emplace_back(spec, std::vector<std::string>());
-               std::vector<std::string> &values = m_dropdowns.back().second;
-               for (const std::string &item : items) {
-                       values.push_back(unescape_string(item));
-               }
+       spec.sound = style.get(StyleSpec::Property::SOUND, "");
 
-               return;
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+
+       m_fields.push_back(spec);
+
+       m_dropdowns.emplace_back(spec, std::vector<std::string>());
+       std::vector<std::string> &values = m_dropdowns.back().second;
+       for (const std::string &item : items) {
+               values.push_back(unescape_string(item));
        }
-       errorstream << "Invalid dropdown element(" << parts.size() << "): '"
-                               << element << "'"  << std::endl;
 }
 
 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
-       if (parts.size() == 2 ||
-                       (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
-               field_close_on_enter[parts[0]] = is_yes(parts[1]);
-       }
+       std::vector<std::string> parts;
+       if (!precheckElement("field_close_on_enter", element, 2, 2, parts))
+               return;
+
+       field_close_on_enter[parts[0]] = is_yes(parts[1]);
 }
 
 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("pwdfield", element, 4, 4, parts))
+               return;
 
-       if ((parts.size() == 4) || (parts.size() == 5) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string name = parts[2];
-               std::string label = parts[3];
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string name = parts[2];
+       std::string label = parts[3];
+
+       MY_CHECKPOS("pwdfield",0);
+       MY_CHECKGEOM("pwdfield",1);
 
-               MY_CHECKPOS("pwdfield",0);
-               MY_CHECKGEOM("pwdfield",1);
+       v2s32 pos;
+       v2s32 geom;
 
-               v2s32 pos;
-               v2s32 geom;
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               pos -= padding;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       pos -= padding;
+               geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
 
-                       geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
+               pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
+               pos.Y -= m_btn_height;
+               geom.Y = m_btn_height*2;
+       }
 
-                       pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
-                       pos.Y -= m_btn_height;
-                       geom.Y = m_btn_height*2;
-               }
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
+       std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
 
-               std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
+       FieldSpec spec(
+               name,
+               wlabel,
+               L"",
+               258 + m_fields.size(),
+               0,
+               ECI_IBEAM
+               );
 
-               FieldSpec spec(
-                       name,
-                       wlabel,
-                       L"",
-                       258+m_fields.size()
-                       );
+       spec.send = true;
+       gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
+                       data->current_parent, spec.fid);
 
-               spec.send = true;
-               gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       if (label.length() >= 1) {
+               int font_height = g_fontengine->getTextHeight();
+               rect.UpperLeftCorner.Y -= font_height;
+               rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
+               gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
+                       data->current_parent, 0);
+       }
 
-               if (label.length() >= 1) {
-                       int font_height = g_fontengine->getTextHeight();
-                       rect.UpperLeftCorner.Y -= font_height;
-                       rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
-                       gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
-                               this, 0);
-               }
+       e->setPasswordBox(true,L'*');
 
-               e->setPasswordBox(true,L'*');
+       auto style = getDefaultStyleForElement("pwdfield", name, "field");
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
+       e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
+       e->setOverrideFont(style.getFont());
 
-               auto style = getStyleForElement("pwdfield", name, "field");
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-               e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
-               e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
+       irr::SEvent evt;
+       evt.EventType            = EET_KEY_INPUT_EVENT;
+       evt.KeyInput.Key         = KEY_END;
+       evt.KeyInput.Char        = 0;
+       evt.KeyInput.Control     = false;
+       evt.KeyInput.Shift       = false;
+       evt.KeyInput.PressedDown = true;
+       e->OnEvent(evt);
 
-               irr::SEvent evt;
-               evt.EventType            = EET_KEY_INPUT_EVENT;
-               evt.KeyInput.Key         = KEY_END;
-               evt.KeyInput.Char        = 0;
-               evt.KeyInput.Control     = false;
-               evt.KeyInput.Shift       = false;
-               evt.KeyInput.PressedDown = true;
-               e->OnEvent(evt);
-
-               if (parts.size() >= 5) {
-                       // TODO: remove after 2016-11-03
-                       warningstream << "pwdfield: use field_close_on_enter[name, enabled]" <<
-                                       " instead of the 5th param" << std::endl;
-                       field_close_on_enter[name] = is_yes(parts[4]);
-               }
+       // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
+       // warning referring to field_close_on_enter[]!
 
-               m_fields.push_back(spec);
-               return;
-       }
-       errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       m_fields.push_back(spec);
 }
 
 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
@@ -1187,7 +1477,7 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
        if (!is_editable && !is_multiline) {
                // spec field id to 0, this stops submit searching for a value that isn't there
                gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
-                       this, spec.fid);
+                               data->current_parent, 0);
                return;
        }
 
@@ -1200,26 +1490,19 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
        }
 
        gui::IGUIEditBox *e = nullptr;
-       static constexpr bool use_intl_edit_box = USE_FREETYPE &&
-               IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
-
-       if (use_intl_edit_box && g_settings->getBool("freetype")) {
-               e = new gui::intlGUIEditBox(spec.fdefault.c_str(),
-                       true, Environment, this, spec.fid, rect, is_editable, is_multiline);
-               e->drop();
-       } else {
-               if (is_multiline) {
-                       e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true,
-                               Environment, this, spec.fid, rect, is_editable, true);
-                       e->drop();
-               } else if (is_editable) {
-                       e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
-                               this, spec.fid);
-               }
+       if (is_multiline) {
+               e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
+                               data->current_parent, spec.fid, rect, is_editable, true);
+       } else if (is_editable) {
+               e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
+                               data->current_parent, spec.fid);
+               e->grab();
        }
 
+       auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
+
        if (e) {
-               if (is_editable && spec.fname == data->focused_fieldname)
+               if (is_editable && spec.fname == m_focused_element)
                        Environment->setFocus(e);
 
                if (is_multiline) {
@@ -1237,26 +1520,30 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
                        e->OnEvent(evt);
                }
 
-               auto style = getStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
                e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-               e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
                e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
-               if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
-                       e->setDrawBackground(false);
-               }
+               bool border = style.getBool(StyleSpec::BORDER, true);
+               e->setDrawBorder(border);
+               e->setDrawBackground(border);
+               e->setOverrideFont(style.getFont());
+
+               e->drop();
        }
 
        if (!spec.flabel.empty()) {
                int font_height = g_fontengine->getTextHeight();
                rect.UpperLeftCorner.Y -= font_height;
                rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
-               gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
-                       this, 0);
+               IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
+                               rect, false, true, data->current_parent, 0);
+
+               if (t)
+                       t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
        }
 }
 
-void GUIFormSpecMenu::parseSimpleField(parserDatadata,
-               std::vector<std::string> &parts)
+void GUIFormSpecMenu::parseSimpleField(parserData *data,
+       std::vector<std::string> &parts)
 {
        std::string name = parts[0];
        std::string label = parts[1];
@@ -1264,18 +1551,20 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data,
 
        core::rect<s32> rect;
 
-       if(data->explicit_size)
-               warningstream<<"invalid use of unpositioned \"field\" in inventory"<<std::endl;
+       if (data->explicit_size)
+               warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
 
-       v2s32 pos = getElementBasePos(false, nullptr);
-       pos.Y = ((m_fields.size()+2)*60);
+       v2s32 pos = getElementBasePos(nullptr);
+       pos.Y = (data->simple_field_count + 2) * 60;
        v2s32 size = DesiredRect.getSize();
 
-       rect = core::rect<s32>(size.X / 2 - 150, pos.Y,
-                       (size.X / 2 - 150) + 300, pos.Y + (m_btn_height*2));
+       rect = core::rect<s32>(
+                       size.X / 2 - 150,       pos.Y,
+                       size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
+       );
 
 
-       if(m_form_src)
+       if (m_form_src)
                default_val = m_form_src->resolveText(default_val);
 
 
@@ -1285,25 +1574,21 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data,
                name,
                wlabel,
                utf8_to_wide(unescape_string(default_val)),
-               258+m_fields.size()
+               258 + m_fields.size(),
+               0,
+               ECI_IBEAM
        );
 
        createTextField(data, spec, rect, false);
 
-       if (parts.size() >= 4) {
-               // TODO: remove after 2016-11-03
-               warningstream << "field/simple: use field_close_on_enter[name, enabled]" <<
-                               " instead of the 4th param" << std::endl;
-               field_close_on_enter[name] = is_yes(parts[3]);
-       }
-
        m_fields.push_back(spec);
+
+       data->simple_field_count++;
 }
 
 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
                const std::string &type)
 {
-
        std::vector<std::string> v_pos = split(parts[0],',');
        std::vector<std::string> v_geom = split(parts[1],',');
        std::string name = parts[2];
@@ -1317,10 +1602,10 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>&
        v2s32 geom;
 
        if (data->real_coordinates) {
-               pos = getRealCoordinateBasePos(false, v_pos);
+               pos = getRealCoordinateBasePos(v_pos);
                geom = getRealCoordinateGeometry(v_geom);
        } else {
-               pos = getElementBasePos(false, &v_pos);
+               pos = getElementBasePos(&v_pos);
                pos -= padding;
 
                geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
@@ -1353,17 +1638,15 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>&
                name,
                wlabel,
                utf8_to_wide(unescape_string(default_val)),
-               258+m_fields.size()
+               258 + m_fields.size(),
+               0,
+               ECI_IBEAM
        );
 
        createTextField(data, spec, rect, type == "textarea");
 
-       if (parts.size() >= 6) {
-               // TODO: remove after 2016-11-03
-               warningstream << "field/textarea: use field_close_on_enter[name, enabled]" <<
-                               " instead of the 6th param" << std::endl;
-               field_close_on_enter[name] = is_yes(parts[5]);
-       }
+       // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
+       // warning referring to field_close_on_enter[]!
 
        m_fields.push_back(spec);
 }
@@ -1371,576 +1654,668 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>&
 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
                const std::string &type)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement(type, element, 3, 5, parts))
+               return;
 
        if (parts.size() == 3 || parts.size() == 4) {
-               parseSimpleField(data,parts);
+               parseSimpleField(data, parts);
                return;
        }
 
-       if ((parts.size() == 5) || (parts.size() == 6) ||
-               ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               parseTextArea(data,parts,type);
-               return;
-       }
-       errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       // Else: >= 5 arguments in "parts"
+       parseTextArea(data, parts, type);
 }
 
-void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
-
-       if ((parts.size() == 2) ||
-               ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::string text = parts[1];
+       MY_CHECKCLIENT("hypertext");
 
-               MY_CHECKPOS("label",0);
+       std::vector<std::string> parts;
+       if (!precheckElement("hypertext", element, 4, 4, parts))
+               return;
 
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of label without a size[] element"<<std::endl;
+       std::vector<std::string> v_pos = split(parts[0], ',');
+       std::vector<std::string> v_geom = split(parts[1], ',');
+       std::string name = parts[2];
+       std::string text = parts[3];
 
-               std::vector<std::string> lines = split(text, '\n');
+       MY_CHECKPOS("hypertext", 0);
+       MY_CHECKGEOM("hypertext", 1);
 
-               for (unsigned int i = 0; i != lines.size(); i++) {
-                       std::wstring wlabel_colors = translate_string(
-                               utf8_to_wide(unescape_string(lines[i])));
-                       // Without color escapes to get the font dimensions
-                       std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
+       v2s32 pos;
+       v2s32 geom;
 
-                       core::rect<s32> rect;
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               pos -= padding;
 
-                       if (data->real_coordinates) {
-                               // Lines are spaced at the distance of 1/2 imgsize.
-                               // This alows lines that line up with the new elements
-                               // easily without sacrificing good line distance.  If
-                               // it was one whole imgsize, it would have too much
-                               // spacing.
-                               v2s32 pos = getRealCoordinateBasePos(false, v_pos);
+               geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
+               geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
+               pos.Y += m_btn_height;
+       }
 
-                               // Labels are positioned by their center, not their top.
-                               pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
 
-                               rect = core::rect<s32>(
-                                       pos.X, pos.Y,
-                                       pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
-                                       pos.Y + imgsize.Y);
+       if(m_form_src)
+               text = m_form_src->resolveText(text);
 
-                       } else {
-                               // Lines are spaced at the nominal distance of
-                               // 2/5 inventory slot, even if the font doesn't
-                               // quite match that.  This provides consistent
-                               // form layout, at the expense of sometimes
-                               // having sub-optimal spacing for the font.
-                               // We multiply by 2 and then divide by 5, rather
-                               // than multiply by 0.4, to get exact results
-                               // in the integer cases: 0.4 is not exactly
-                               // representable in binary floating point.
-
-                               v2s32 pos = getElementBasePos(false, nullptr);
-                               pos.X += stof(v_pos[0]) * spacing.X;
-                               pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
-
-                               pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
-
-                               rect = core::rect<s32>(
-                                       pos.X, pos.Y - m_btn_height,
-                                       pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
-                                       pos.Y + m_btn_height);
-                       }
+       FieldSpec spec(
+               name,
+               translate_string(utf8_to_wide(unescape_string(text))),
+               L"",
+               258 + m_fields.size()
+       );
 
-                       FieldSpec spec(
-                               "",
-                               wlabel_colors,
-                               L"",
-                               258+m_fields.size()
-                       );
-                       gui::IGUIStaticText *e = gui::StaticText::add(Environment,
-                               spec.flabel.c_str(), rect, false, false, this, spec.fid);
-                       e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
+       spec.ftype = f_HyperText;
 
-                       auto style = getStyleForElement("label", spec.fname);
-                       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-                       e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
+       auto style = getDefaultStyleForElement("hypertext", spec.fname);
+       spec.sound = style.get(StyleSpec::Property::SOUND, "");
 
-                       m_fields.push_back(spec);
-               }
+       GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
+                       data->current_parent, spec.fid, rect, m_client, m_tsrc);
+       e->drop();
 
-               return;
-       }
-       errorstream << "Invalid label element(" << parts.size() << "): '" << element
-               << "'"  << std::endl;
+       m_fields.push_back(spec);
 }
 
-void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("label", element, 2, 2, parts))
+               return;
 
-       if ((parts.size() == 2) ||
-               ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::wstring text = unescape_translate(
-                       unescape_string(utf8_to_wide(parts[1])));
+       std::vector<std::string> v_pos = split(parts[0],',');
 
-               MY_CHECKPOS("vertlabel",1);
+       MY_CHECKPOS("label",0);
+
+       if(!data->explicit_size)
+               warningstream<<"invalid use of label without a size[] element"<<std::endl;
+
+       auto style = getDefaultStyleForElement("label", "");
+       gui::IGUIFont *font = style.getFont();
+       if (!font)
+               font = m_font;
+
+       EnrichedString str(unescape_string(utf8_to_wide(parts[1])));
+       size_t str_pos = 0;
+
+       for (size_t i = 0; str_pos < str.size(); ++i) {
+               // Split per line
+               size_t str_nl = str.getString().find(L'\n', str_pos);
+               if (str_nl == std::wstring::npos)
+                       str_nl = str.getString().size();
+               EnrichedString line = str.substr(str_pos, str_nl - str_pos);
+               str_pos += line.size() + 1;
 
-               v2s32 pos;
                core::rect<s32> rect;
 
                if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
+                       // Lines are spaced at the distance of 1/2 imgsize.
+                       // This alows lines that line up with the new elements
+                       // easily without sacrificing good line distance.  If
+                       // it was one whole imgsize, it would have too much
+                       // spacing.
+                       v2s32 pos = getRealCoordinateBasePos(v_pos);
 
-                       // Vertlabels are positioned by center, not left.
-                       pos.X -= imgsize.X / 2;
+                       // Labels are positioned by their center, not their top.
+                       pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
 
-                       // We use text.length + 1 because without it, the rect
-                       // isn't quite tall enough and cuts off the text.
-                       rect = core::rect<s32>(pos.X, pos.Y,
-                               pos.X + imgsize.X,
-                               pos.Y + font_line_height(m_font) *
-                               (text.length() + 1));
+                       rect = core::rect<s32>(
+                               pos.X, pos.Y,
+                               pos.X + font->getDimension(line.c_str()).Width,
+                               pos.Y + imgsize.Y);
 
                } else {
-                       pos = getElementBasePos(false, &v_pos);
+                       // Lines are spaced at the nominal distance of
+                       // 2/5 inventory slot, even if the font doesn't
+                       // quite match that.  This provides consistent
+                       // form layout, at the expense of sometimes
+                       // having sub-optimal spacing for the font.
+                       // We multiply by 2 and then divide by 5, rather
+                       // than multiply by 0.4, to get exact results
+                       // in the integer cases: 0.4 is not exactly
+                       // representable in binary floating point.
+
+                       v2s32 pos = getElementBasePos(nullptr);
+                       pos.X += stof(v_pos[0]) * spacing.X;
+                       pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
+
+                       pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
 
-                       // As above, the length must be one longer. The width of
-                       // the rect (15 pixels) seems rather arbitrary, but
-                       // changing it might break something.
                        rect = core::rect<s32>(
-                               pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
-                               pos.X+15, pos.Y +
-                                       font_line_height(m_font) *
-                                       (text.length() + 1) +
-                                       ((imgsize.Y/2) - m_btn_height));
-               }
-
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of label without a size[] element"<<std::endl;
-
-               std::wstring label;
-
-               for (wchar_t i : text) {
-                       label += i;
-                       label += L"\n";
+                               pos.X, pos.Y - m_btn_height,
+                               pos.X + font->getDimension(line.c_str()).Width,
+                               pos.Y + m_btn_height);
                }
 
                FieldSpec spec(
                        "",
-                       label,
                        L"",
-                       258+m_fields.size()
+                       L"",
+                       258 + m_fields.size(),
+                       4
                );
-               gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
-                       rect, false, false, this, spec.fid);
-               e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
+               gui::IGUIStaticText *e = gui::StaticText::add(Environment,
+                               line, rect, false, false, data->current_parent,
+                               spec.fid);
+               e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
 
-               auto style = getStyleForElement("vertlabel", spec.fname, "label");
                e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
                e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
+               e->setOverrideFont(font);
 
                m_fields.push_back(spec);
+
+               // labels should let events through
+               e->grab();
+               m_clickthrough_elements.push_back(e);
+       }
+}
+
+void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
+{
+       std::vector<std::string> parts;
+       if (!precheckElement("vertlabel", element, 2, 2, parts))
                return;
+
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::wstring text = unescape_translate(
+               unescape_string(utf8_to_wide(parts[1])));
+
+       MY_CHECKPOS("vertlabel",1);
+
+       auto style = getDefaultStyleForElement("vertlabel", "", "label");
+       gui::IGUIFont *font = style.getFont();
+       if (!font)
+               font = m_font;
+
+       v2s32 pos;
+       core::rect<s32> rect;
+
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+
+               // Vertlabels are positioned by center, not left.
+               pos.X -= imgsize.X / 2;
+
+               // We use text.length + 1 because without it, the rect
+               // isn't quite tall enough and cuts off the text.
+               rect = core::rect<s32>(pos.X, pos.Y,
+                       pos.X + imgsize.X,
+                       pos.Y + font_line_height(font) *
+                       (text.length() + 1));
+
+       } else {
+               pos = getElementBasePos(&v_pos);
+
+               // As above, the length must be one longer. The width of
+               // the rect (15 pixels) seems rather arbitrary, but
+               // changing it might break something.
+               rect = core::rect<s32>(
+                       pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
+                       pos.X+15, pos.Y +
+                               font_line_height(font) *
+                               (text.length() + 1) +
+                               ((imgsize.Y/2) - m_btn_height));
+       }
+
+       if(!data->explicit_size)
+               warningstream<<"invalid use of label without a size[] element"<<std::endl;
+
+       std::wstring label;
+
+       for (wchar_t i : text) {
+               label += i;
+               label += L"\n";
        }
-       errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       FieldSpec spec(
+               "",
+               label,
+               L"",
+               258 + m_fields.size()
+       );
+       gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
+                       rect, false, false, data->current_parent, spec.fid);
+       e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
+
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
+       e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
+       e->setOverrideFont(font);
+
+       m_fields.push_back(spec);
+
+       // vertlabels should let events through
+       e->grab();
+       m_clickthrough_elements.push_back(e);
 }
 
 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
                const std::string &type)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("image_button", element, 5, 8, parts))
+               return;
 
-       if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
-               ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string image_name = parts[2];
-               std::string name = parts[3];
-               std::string label = parts[4];
-
-               MY_CHECKPOS("imagebutton",0);
-               MY_CHECKGEOM("imagebutton",1);
-
-               bool noclip     = false;
-               bool drawborder = true;
-               std::string pressed_image_name;
-
-               if (parts.size() >= 7) {
-                       if (parts[5] == "true")
-                               noclip = true;
-                       if (parts[6] == "false")
-                               drawborder = false;
-               }
+       if (parts.size() == 6) {
+               // Invalid argument count.
+               errorstream << "Invalid image_button element(" << parts.size() << "): '" << element << "'" << std::endl;
+               return;
+       }
 
-               if (parts.size() >= 8) {
-                       pressed_image_name = parts[7];
-               }
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string image_name = parts[2];
+       std::string name = parts[3];
+       std::string label = parts[4];
 
-               v2s32 pos;
-               v2s32 geom;
+       MY_CHECKPOS("image_button",0);
+       MY_CHECKGEOM("image_button",1);
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
-                       geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
-               }
+       std::string pressed_image_name;
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
-                       pos.Y+geom.Y);
+       if (parts.size() >= 8) {
+               pressed_image_name = parts[7];
+       }
 
-               if (!data->explicit_size)
-                       warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
+       v2s32 pos;
+       v2s32 geom;
 
-               image_name = unescape_string(image_name);
-               pressed_image_name = unescape_string(pressed_image_name);
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
+               geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
+       }
 
-               std::wstring wlabel = utf8_to_wide(unescape_string(label));
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
+               pos.Y+geom.Y);
 
-               FieldSpec spec(
-                       name,
-                       wlabel,
-                       utf8_to_wide(image_name),
-                       258+m_fields.size()
-               );
-               spec.ftype = f_Button;
-               if (type == "image_button_exit")
-                       spec.is_exit = true;
-
-               video::ITexture *texture = 0;
-               video::ITexture *pressed_texture = 0;
-               texture = m_tsrc->getTexture(image_name);
-               if (!pressed_image_name.empty())
-                       pressed_texture = m_tsrc->getTexture(pressed_image_name);
-               else
-                       pressed_texture = texture;
+       if (!data->explicit_size)
+               warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
 
-               gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
+       image_name = unescape_string(image_name);
+       pressed_image_name = unescape_string(pressed_image_name);
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       std::wstring wlabel = utf8_to_wide(unescape_string(label));
 
-               auto style = getStyleForElement("image_button", spec.fname);
-
-               e->setUseAlphaChannel(style.getBool(StyleSpec::ALPHA, true));
-               e->setImage(guiScalingImageButton(
-                       Environment->getVideoDriver(), texture, geom.X, geom.Y));
-               e->setPressedImage(guiScalingImageButton(
-                       Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
-               e->setScaleImage(true);
-               if (parts.size() >= 7) {
-                       e->setNotClipped(noclip);
-                       e->setDrawBorder(drawborder);
-               } else {
-                       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-                       e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
-               }
+       FieldSpec spec(
+               name,
+               wlabel,
+               utf8_to_wide(image_name),
+               258 + m_fields.size()
+       );
+       spec.ftype = f_Button;
+       if (type == "image_button_exit")
+               spec.is_exit = true;
 
-               m_fields.push_back(spec);
-               return;
+       GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
+                       data->current_parent, spec.fid, spec.flabel.c_str());
+
+       if (spec.fname == m_focused_element) {
+               Environment->setFocus(e);
+       }
+
+       auto style = getStyleForElement("image_button", spec.fname);
+
+       spec.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
+
+       // Override style properties with values specified directly in the element
+       if (!image_name.empty())
+               style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
+
+       if (!pressed_image_name.empty())
+               style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
+
+       if (parts.size() >= 7) {
+               style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
+               style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
        }
 
-       errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       e->setStyles(style);
+       e->setScaleImage(true);
+
+       m_fields.push_back(spec);
 }
 
 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element, ';');
-
-       if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
-               data->real_coordinates) || ((parts.size() > 6) &&
-               (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-
-               // If we're using real coordinates, add an extra field for height.
-               // Width is not here because tabs are the width of the text, and
-               // there's no reason to change that.
-               unsigned int i = 0;
-               std::vector<std::string> v_geom = {"1", "0.75"}; // Dummy width and default height
-               bool auto_width = true;
-               if (parts.size() == 7) {
-                       i++;
+       std::vector<std::string> parts;
+       if (!precheckElement("tabheader", element, 4, 7, parts))
+               return;
 
-                       v_geom = split(parts[1], ',');
-                       if (v_geom.size() == 1)
-                               v_geom.insert(v_geom.begin(), "1"); // Dummy value
-                       else
-                               auto_width = false;
-               }
+       // Length 7: Additional "height" parameter after "pos". Only valid with real_coordinates.
+       // Note: New arguments for the "height" syntax cannot be added without breaking older clients.
+       if (parts.size() == 5 || (parts.size() == 7 && !data->real_coordinates)) {
+               errorstream << "Invalid tabheader element(" << parts.size() << "): '"
+                       << element << "'" << std::endl;
+               return;
+       }
 
-               std::string name = parts[i+1];
-               std::vector<std::string> buttons = split(parts[i+2], ',');
-               std::string str_index = parts[i+3];
-               bool show_background = true;
-               bool show_border = true;
-               int tab_index = stoi(str_index) - 1;
+       std::vector<std::string> v_pos = split(parts[0],',');
 
-               MY_CHECKPOS("tabheader", 0);
+       // If we're using real coordinates, add an extra field for height.
+       // Width is not here because tabs are the width of the text, and
+       // there's no reason to change that.
+       unsigned int i = 0;
+       std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
+       bool auto_width = true;
+       if (parts.size() == 7) {
+               i++;
+
+               v_geom = split(parts[1], ',');
+               if (v_geom.size() == 1)
+                       v_geom.insert(v_geom.begin(), "1"); // Dummy value
+               else
+                       auto_width = false;
+       }
 
-               if (parts.size() == 6 + i) {
-                       if (parts[4+i] == "true")
-                               show_background = false;
-                       if (parts[5+i] == "false")
-                               show_border = false;
-               }
+       std::string name = parts[i+1];
+       std::vector<std::string> buttons = split(parts[i+2], ',');
+       std::string str_index = parts[i+3];
+       bool show_background = true;
+       bool show_border = true;
+       int tab_index = stoi(str_index) - 1;
 
-               FieldSpec spec(
-                       name,
-                       L"",
-                       L"",
-                       258+m_fields.size()
-               );
+       MY_CHECKPOS("tabheader", 0);
 
-               spec.ftype = f_TabHeader;
+       if (parts.size() == 6 + i) {
+               if (parts[4+i] == "true")
+                       show_background = false;
+               if (parts[5+i] == "false")
+                       show_border = false;
+       }
 
-               v2s32 pos;
-               v2s32 geom;
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
+       spec.ftype = f_TabHeader;
 
-                       geom = getRealCoordinateGeometry(v_geom);
-                       pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
-                       if (auto_width)
-                               geom.X = DesiredRect.getWidth(); // Set automatic width
+       v2s32 pos;
+       v2s32 geom;
 
-                       MY_CHECKGEOM("tabheader", 1);
-               } else {
-                       v2f32 pos_f = pos_offset * spacing;
-                       pos_f.X += stof(v_pos[0]) * spacing.X;
-                       pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
-                       pos = v2s32(pos_f.X, pos_f.Y);
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
 
+               geom = getRealCoordinateGeometry(v_geom);
+               // Set default height
+               if (parts.size() <= 6)
                        geom.Y = m_btn_height * 2;
-                       geom.X = DesiredRect.getWidth();
-               }
+               pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
+               if (auto_width)
+                       geom.X = DesiredRect.getWidth(); // Set automatic width
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
-                               pos.Y+geom.Y);
+               MY_CHECKGEOM("tabheader", 1);
+       } else {
+               v2f32 pos_f = pos_offset * spacing;
+               pos_f.X += stof(v_pos[0]) * spacing.X;
+               pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
+               pos = v2s32(pos_f.X, pos_f.Y);
 
-               gui::IGUITabControl *e = Environment->addTabControl(rect, this,
-                               show_background, show_border, spec.fid);
-               e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
-                               irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
-               e->setTabHeight(geom.Y);
+               geom.Y = m_btn_height * 2;
+               geom.X = DesiredRect.getWidth();
+       }
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
+                       pos.Y+geom.Y);
 
-               auto style = getStyleForElement("tabheader", name);
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
+       gui::IGUITabControl *e = Environment->addTabControl(rect,
+                       data->current_parent, show_background, show_border, spec.fid);
+       e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
+                       irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
+       e->setTabHeight(geom.Y);
 
-               for (const std::string &button : buttons) {
-                       auto tab = e->addTab(unescape_translate(unescape_string(
-                               utf8_to_wide(button))).c_str(), -1);
-                       if (style.isNotDefault(StyleSpec::BGCOLOR))
-                               tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
+       auto style = getDefaultStyleForElement("tabheader", name);
 
-                       tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
-               }
+       spec.sound = style.get(StyleSpec::Property::SOUND, "");
 
-               if ((tab_index >= 0) &&
-                               (buttons.size() < INT_MAX) &&
-                               (tab_index < (int) buttons.size()))
-                       e->setActiveTab(tab_index);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
 
-               m_fields.push_back(spec);
-               return;
+       for (const std::string &button : buttons) {
+               auto tab = e->addTab(unescape_translate(unescape_string(
+                       utf8_to_wide(button))).c_str(), -1);
+               if (style.isNotDefault(StyleSpec::BGCOLOR))
+                       tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
+
+               tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
        }
-       errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
-                       << element << "'"  << std::endl;
+
+       if ((tab_index >= 0) &&
+                       (buttons.size() < INT_MAX) &&
+                       (tab_index < (int) buttons.size()))
+               e->setActiveTab(tab_index);
+
+       m_fields.push_back(spec);
 }
 
 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
 {
+       MY_CHECKCLIENT("item_image_button");
 
-       if (m_client == 0) {
-               warningstream << "invalid use of item_image_button with m_client==0"
-                       << std::endl;
+       std::vector<std::string> parts;
+       if (!precheckElement("item_image_button", element, 5, 5, parts))
                return;
-       }
-
-       std::vector<std::string> parts = split(element,';');
-
-       if ((parts.size() == 5) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
-               std::string item_name = parts[2];
-               std::string name = parts[3];
-               std::string label = parts[4];
 
-               label = unescape_string(label);
-               item_name = unescape_string(item_name);
+       std::vector<std::string> v_pos = split(parts[0],',');
+       std::vector<std::string> v_geom = split(parts[1],',');
+       std::string item_name = parts[2];
+       std::string name = parts[3];
+       std::string label = parts[4];
 
-               MY_CHECKPOS("itemimagebutton",0);
-               MY_CHECKGEOM("itemimagebutton",1);
+       label = unescape_string(label);
+       item_name = unescape_string(item_name);
 
-               v2s32 pos;
-               v2s32 geom;
+       MY_CHECKPOS("item_image_button",0);
+       MY_CHECKGEOM("item_image_button",1);
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(false, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(false, &v_pos);
-                       geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
-                       geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
-               }
+       v2s32 pos;
+       v2s32 geom;
 
-               core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
+               geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
+       }
 
-               if(!data->explicit_size)
-                       warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
+       core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
 
-               IItemDefManager *idef = m_client->idef();
-               ItemStack item;
-               item.deSerialize(item_name, idef);
+       if(!data->explicit_size)
+               warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
 
-               m_tooltips[name] =
-                       TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
-                                               m_default_tooltip_bgcolor,
-                                               m_default_tooltip_color);
+       IItemDefManager *idef = m_client->idef();
+       ItemStack item;
+       item.deSerialize(item_name, idef);
 
-               FieldSpec spec(
-                       name,
-                       utf8_to_wide(label),
-                       utf8_to_wide(item_name),
-                       258 + m_fields.size()
-               );
+       m_tooltips[name] =
+               TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
+                                       m_default_tooltip_bgcolor,
+                                       m_default_tooltip_color);
 
-               gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, L"");
+       // the spec for the button
+       FieldSpec spec_btn(
+               name,
+               utf8_to_wide(label),
+               utf8_to_wide(item_name),
+               258 + m_fields.size(),
+               2
+       );
 
-               auto style = getStyleForElement("item_image_button", spec.fname, "image_button");
-               e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
-               e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
+       GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
+                       rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
+                       item_name, m_client);
 
-               if (spec.fname == data->focused_fieldname) {
-                       Environment->setFocus(e);
-               }
+       auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
 
-               spec.ftype = f_Button;
-               rect+=data->basepos-padding;
-               spec.rect=rect;
-               m_fields.push_back(spec);
+       spec_btn.sound = style[StyleSpec::STATE_DEFAULT].get(StyleSpec::Property::SOUND, "");
 
-               if (data->real_coordinates)
-                       pos = getRealCoordinateBasePos(true, v_pos);
-               else
-                       pos = getElementBasePos(true, &v_pos);
+       e_btn->setStyles(style);
 
-               m_itemimages.emplace_back("", item_name, e, pos, geom);
-               m_static_texts.emplace_back(utf8_to_wide(label), rect, e);
-               return;
+       if (spec_btn.fname == m_focused_element) {
+               Environment->setFocus(e_btn);
        }
-       errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       spec_btn.ftype = f_Button;
+       rect += data->basepos-padding;
+       spec_btn.rect = rect;
+       m_fields.push_back(spec_btn);
 }
 
 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("box", element, 3, 3, parts))
+               return;
 
-       if ((parts.size() == 3) ||
-               ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               std::vector<std::string> v_pos = split(parts[0],',');
-               std::vector<std::string> v_geom = split(parts[1],',');
+       std::vector<std::string> v_pos = split(parts[0], ',');
+       std::vector<std::string> v_geom = split(parts[1], ',');
 
-               MY_CHECKPOS("box",0);
-               MY_CHECKGEOM("box",1);
+       MY_CHECKPOS("box", 0);
+       MY_CHECKGEOM("box", 1);
 
-               v2s32 pos;
-               v2s32 geom;
+       v2s32 pos;
+       v2s32 geom;
 
-               if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(true, v_pos);
-                       geom = getRealCoordinateGeometry(v_geom);
-               } else {
-                       pos = getElementBasePos(true, &v_pos);
-                       geom.X = stof(v_geom[0]) * spacing.X;
-                       geom.Y = stof(v_geom[1]) * spacing.Y;
-               }
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * spacing.X;
+               geom.Y = stof(v_geom[1]) * spacing.Y;
+       }
 
-               video::SColor tmp_color;
+       FieldSpec spec(
+               "",
+               L"",
+               L"",
+               258 + m_fields.size(),
+               -2
+       );
+       spec.ftype = f_Box;
 
-               if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
-                       BoxDrawSpec spec(pos, geom, tmp_color);
+       auto style = getDefaultStyleForElement("box", spec.fname);
 
-                       m_boxes.push_back(spec);
-               }
-               else {
-                       errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
-               }
-               return;
+       video::SColor tmp_color;
+       std::array<video::SColor, 4> colors;
+       std::array<video::SColor, 4> bordercolors = {0x0, 0x0, 0x0, 0x0};
+       std::array<s32, 4> borderwidths = {0, 0, 0, 0};
+
+       if (parseColorString(parts[2], tmp_color, true, 0x8C)) {
+               colors = {tmp_color, tmp_color, tmp_color, tmp_color};
+       } else {
+               colors = style.getColorArray(StyleSpec::COLORS, {0x0, 0x0, 0x0, 0x0});
+               bordercolors = style.getColorArray(StyleSpec::BORDERCOLORS,
+                       {0x0, 0x0, 0x0, 0x0});
+               borderwidths = style.getIntArray(StyleSpec::BORDERWIDTHS, {0, 0, 0, 0});
        }
-       errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
+
+       core::rect<s32> rect(pos, pos + geom);
+
+       GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid, rect,
+               colors, bordercolors, borderwidths);
+       e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
+       e->drop();
+
+       m_fields.push_back(spec);
 }
 
-void GUIFormSpecMenu::parseBackgroundColor(parserData *data, const std::string &element)
+void GUIFormSpecMenu::parseBackgroundColor(parserDatadata, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       if (!precheckElement("bgcolor", element, 1, 3, parts))
+               return;
 
-       if (((parts.size() == 1) || (parts.size() == 2)) ||
-                       ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) {
-               if (parts.size() == 1) {
-                       parseColorString(parts[0], m_bgcolor, false);
-               } else if (parts.size() == 2) {
-                       parseColorString(parts[0], m_fullscreen_bgcolor, false);
-                       m_bgfullscreen = is_yes(parts[1]);
-               }
+       const u32 parameter_count = parts.size();
 
+       if (parameter_count > 2 && m_formspec_version < 3) {
+               errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
+                               << element << "'" << std::endl;
                return;
        }
 
-       errorstream << "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"
-                       << std::endl;
+       // bgcolor
+       if (parameter_count >= 1 && !parts[0].empty())
+               parseColorString(parts[0], m_bgcolor, false);
+
+       // fullscreen
+       if (parameter_count >= 2) {
+               if (parts[1] == "both") {
+                       m_bgnonfullscreen = true;
+                       m_bgfullscreen = true;
+               } else if (parts[1] == "neither") {
+                       m_bgnonfullscreen = false;
+                       m_bgfullscreen = false;
+               } else if (!parts[1].empty() || m_formspec_version < 3) {
+                       m_bgfullscreen = is_yes(parts[1]);
+                       m_bgnonfullscreen = !m_bgfullscreen;
+               }
+       }
+
+       // fbgcolor
+       if (parameter_count >= 3 && !parts[2].empty())
+               parseColorString(parts[2], m_fullscreen_bgcolor, false);
 }
 
 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
+       std::vector<std::string> parts;
+       // Legacy Note: If clients older than 5.5.0-dev are supplied with additional arguments,
+       // the tooltip colors will be ignored.
+       if (!precheckElement("listcolors", element, 2, 5, parts))
+               return;
 
-       if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
-               ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
-       {
-               parseColorString(parts[0], m_slotbg_n, false);
-               parseColorString(parts[1], m_slotbg_h, false);
+       if (parts.size() == 4) {
+               // Invalid argument combination
+               errorstream << "Invalid listcolors element(" << parts.size() << "): '"
+                               << element << "'" << std::endl;
+               return;
+       }
 
-               if (parts.size() >= 3) {
-                       if (parseColorString(parts[2], m_slotbordercolor, false)) {
-                               m_slotborder = true;
-                       }
-               }
-               if (parts.size() == 5) {
-                       video::SColor tmp_color;
+       parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
+       parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
 
-                       if (parseColorString(parts[3], tmp_color, false))
-                               m_default_tooltip_bgcolor = tmp_color;
-                       if (parseColorString(parts[4], tmp_color, false))
-                               m_default_tooltip_color = tmp_color;
+       if (parts.size() >= 3) {
+               if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
+                               false)) {
+                       data->inventorylist_options.slotborder = true;
                }
-               return;
        }
-       errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
+       if (parts.size() >= 5) {
+               video::SColor tmp_color;
+
+               if (parseColorString(parts[3], tmp_color, false))
+                       m_default_tooltip_bgcolor = tmp_color;
+               if (parseColorString(parts[4], tmp_color, false))
+                       m_default_tooltip_color = tmp_color;
+       }
+
+       // update all already parsed inventorylists
+       for (GUIInventoryList *e : m_inventorylists) {
+               e->setSlotBGColors(data->inventorylist_options.slotbg_n,
+                               data->inventorylist_options.slotbg_h);
+               e->setSlotBorders(data->inventorylist_options.slotborder,
+                               data->inventorylist_options.slotbordercolor);
+       }
 }
 
 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element,';');
-       if (parts.size() < 2) {
-               errorstream << "Invalid tooltip element(" << parts.size() << "): '"
-                               << element << "'"  << std::endl;
+       std::vector<std::string> parts;
+       if (!precheckElement("tooltip", element, 2, 5, parts))
                return;
-       }
 
        // Get mode and check size
        bool rect_mode = parts[0].find(',') != std::string::npos;
@@ -1978,16 +2353,32 @@ void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
                v2s32 geom;
 
                if (data->real_coordinates) {
-                       pos = getRealCoordinateBasePos(true, v_pos);
+                       pos = getRealCoordinateBasePos(v_pos);
                        geom = getRealCoordinateGeometry(v_geom);
                } else {
-                       pos = getElementBasePos(true, &v_pos);
+                       pos = getElementBasePos(&v_pos);
                        geom.X = stof(v_geom[0]) * spacing.X;
                        geom.Y = stof(v_geom[1]) * spacing.Y;
                }
 
-               irr::core::rect<s32> rect(pos, pos + geom);
-               m_tooltip_rects.emplace_back(rect, spec);
+               FieldSpec fieldspec(
+                       "",
+                       L"",
+                       L"",
+                       258 + m_fields.size()
+               );
+
+               core::rect<s32> rect(pos, pos + geom);
+
+               gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
+                               data->current_parent, fieldspec.fid, rect);
+
+               // the element the rect tooltip is bound to should not block mouse-clicks
+               e->setVisible(false);
+
+               m_fields.push_back(fieldspec);
+               m_tooltip_rects.emplace_back(e, spec);
+
        } else {
                m_tooltips[parts[0]] = spec;
        }
@@ -2005,7 +2396,7 @@ bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
                return false;
        }
 
-       if (parts[0] != "formspec_version") {
+       if (trim(parts[0]) != "formspec_version") {
                return false;
        }
 
@@ -2034,7 +2425,7 @@ bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &eleme
                return false;
 
        if (type == "invsize")
-               log_deprecated("Deprecated formspec element \"invsize\" is used");
+               warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
 
        parseSize(data, description);
 
@@ -2064,11 +2455,16 @@ bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &e
 
 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element, ',');
+       std::vector<std::string> parts = split(element, ';');
 
-       if (parts.size() == 2) {
-               data->offset.X = stof(parts[0]);
-               data->offset.Y = stof(parts[1]);
+       if (parts.size() == 1 ||
+                       (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
+               std::vector<std::string> v_geom = split(parts[0], ',');
+
+               MY_CHECKGEOM("position", 0);
+
+               data->offset.X = stof(v_geom[0]);
+               data->offset.Y = stof(v_geom[1]);
                return;
        }
 
@@ -2098,11 +2494,16 @@ bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &ele
 
 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
 {
-       std::vector<std::string> parts = split(element, ',');
+       std::vector<std::string> parts = split(element, ';');
 
-       if (parts.size() == 2) {
-               data->anchor.X = stof(parts[0]);
-               data->anchor.Y = stof(parts[1]);
+       if (parts.size() == 1 ||
+                       (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
+               std::vector<std::string> v_geom = split(parts[0], ',');
+
+               MY_CHECKGEOM("anchor", 0);
+
+               data->anchor.X = stof(v_geom[0]);
+               data->anchor.Y = stof(v_geom[1]);
                return;
        }
 
@@ -2110,6 +2511,46 @@ void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
                        << "'" << std::endl;
 }
 
+bool GUIFormSpecMenu::parsePaddingDirect(parserData *data, const std::string &element)
+{
+       if (element.empty())
+               return false;
+
+       std::vector<std::string> parts = split(element, '[');
+
+       if (parts.size() != 2)
+               return false;
+
+       std::string type = trim(parts[0]);
+       std::string description = trim(parts[1]);
+
+       if (type != "padding")
+               return false;
+
+       parsePadding(data, description);
+
+       return true;
+}
+
+void GUIFormSpecMenu::parsePadding(parserData *data, const std::string &element)
+{
+       std::vector<std::string> parts = split(element, ';');
+
+       if (parts.size() == 1 ||
+                       (parts.size() > 1 && m_formspec_version > FORMSPEC_API_VERSION)) {
+               std::vector<std::string> v_geom = split(parts[0], ',');
+
+               MY_CHECKGEOM("padding", 0);
+
+               data->padding.X = stof(v_geom[0]);
+               data->padding.Y = stof(v_geom[1]);
+               return;
+       }
+
+       errorstream << "Invalid padding element (" << parts.size() << "): '" << element
+                       << "'" << std::endl;
+}
+
 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
 {
        std::vector<std::string> parts = split(element, ';');
@@ -2120,15 +2561,9 @@ bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, b
                return false;
        }
 
-       std::string selector = trim(parts[0]);
-       if (selector.empty()) {
-               errorstream << "Invalid style element (Selector required): '" << element
-                                       << "'" << std::endl;
-               return false;
-       }
-
        StyleSpec spec;
 
+       // Parse properties
        for (size_t i = 1; i < parts.size(); i++) {
                size_t equal_pos = parts[i].find('=');
                if (equal_pos == std::string::npos) {
@@ -2150,48 +2585,249 @@ bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, b
                                                << "'" << std::endl;
                                property_warned.insert(propname);
                        }
-                       return false;
+                       continue;
                }
 
                spec.set(prop, value);
        }
 
-       if (style_type) {
-               theme_by_type[selector] |= spec;
-       } else {
-               theme_by_name[selector] |= spec;
+       std::vector<std::string> selectors = split(parts[0], ',');
+       for (size_t sel = 0; sel < selectors.size(); sel++) {
+               std::string selector = trim(selectors[sel]);
+
+               // Copy the style properties to a new StyleSpec
+               // This allows a separate state mask per-selector
+               StyleSpec selector_spec = spec;
+
+               // Parse state information, if it exists
+               bool state_valid = true;
+               size_t state_pos = selector.find(':');
+               if (state_pos != std::string::npos) {
+                       std::string state_str = selector.substr(state_pos + 1);
+                       selector = selector.substr(0, state_pos);
+
+                       if (state_str.empty()) {
+                               errorstream << "Invalid style element (Invalid state): '" << element
+                                       << "'" << std::endl;
+                               state_valid = false;
+                       } else {
+                               std::vector<std::string> states = split(state_str, '+');
+                               for (std::string &state : states) {
+                                       StyleSpec::State converted = StyleSpec::getStateByName(state);
+                                       if (converted == StyleSpec::STATE_INVALID) {
+                                               infostream << "Unknown style state " << state <<
+                                                       " in element '" << element << "'" << std::endl;
+                                               state_valid = false;
+                                               break;
+                                       }
+
+                                       selector_spec.addState(converted);
+                               }
+                       }
+               }
+
+               if (!state_valid) {
+                       // Skip this selector
+                       continue;
+               }
+
+               if (style_type) {
+                       theme_by_type[selector].push_back(selector_spec);
+               } else {
+                       theme_by_name[selector].push_back(selector_spec);
+               }
+
+               // Backwards-compatibility for existing _hovered/_pressed properties
+               if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
+                               || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
+                               || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
+                       StyleSpec hover_spec;
+                       hover_spec.addState(StyleSpec::STATE_HOVERED);
+
+                       if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
+                               hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
+                       }
+                       if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
+                               hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
+                       }
+                       if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
+                               hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
+                       }
+
+                       if (style_type) {
+                               theme_by_type[selector].push_back(hover_spec);
+                       } else {
+                               theme_by_name[selector].push_back(hover_spec);
+                       }
+               }
+               if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
+                               || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
+                               || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
+                       StyleSpec press_spec;
+                       press_spec.addState(StyleSpec::STATE_PRESSED);
+
+                       if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
+                               press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
+                       }
+                       if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
+                               press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
+                       }
+                       if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
+                               press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
+                       }
+
+                       if (style_type) {
+                               theme_by_type[selector].push_back(press_spec);
+                       } else {
+                               theme_by_name[selector].push_back(press_spec);
+                       }
+               }
        }
 
        return true;
 }
 
-void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
+void GUIFormSpecMenu::parseSetFocus(const std::string &element)
 {
-       //some prechecks
-       if (element.empty())
+       std::vector<std::string> parts;
+       if (!precheckElement("set_focus", element, 1, 2, parts))
                return;
 
-       if (parseVersionDirect(element))
+       if (m_is_form_regenerated)
+               return; // Never focus on resizing
+
+       bool force_focus = parts.size() >= 2 && is_yes(parts[1]);
+       if (force_focus || m_text_dst->m_formname != m_last_formname)
+               setFocus(parts[0]);
+}
+
+void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element)
+{
+       MY_CHECKCLIENT("model");
+
+       std::vector<std::string> parts;
+       if (!precheckElement("model", element, 5, 10, parts))
                return;
 
-       std::vector<std::string> parts = split(element,'[');
+       // Avoid length checks by resizing
+       if (parts.size() < 10)
+               parts.resize(10);
 
-       // ugly workaround to keep compatibility
-       if (parts.size() > 2) {
-               if (trim(parts[0]) == "image") {
-                       for (unsigned int i=2;i< parts.size(); i++) {
-                               parts[1] += "[" + parts[i];
-                       }
-               }
-               else { return; }
+       std::vector<std::string> v_pos = split(parts[0], ',');
+       std::vector<std::string> v_geom = split(parts[1], ',');
+       std::string name = unescape_string(parts[2]);
+       std::string meshstr = unescape_string(parts[3]);
+       std::vector<std::string> textures = split(parts[4], ',');
+       std::vector<std::string> vec_rot = split(parts[5], ',');
+       bool inf_rotation = is_yes(parts[6]);
+       bool mousectrl = is_yes(parts[7]) || parts[7].empty(); // default true
+       std::vector<std::string> frame_loop = split(parts[8], ',');
+       std::string speed = unescape_string(parts[9]);
+
+       MY_CHECKPOS("model", 0);
+       MY_CHECKGEOM("model", 1);
+
+       v2s32 pos;
+       v2s32 geom;
+
+       if (data->real_coordinates) {
+               pos = getRealCoordinateBasePos(v_pos);
+               geom = getRealCoordinateGeometry(v_geom);
+       } else {
+               pos = getElementBasePos(&v_pos);
+               geom.X = stof(v_geom[0]) * (float)imgsize.X;
+               geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
        }
 
-       if (parts.size() < 2) {
+       if (!data->explicit_size)
+               warningstream << "invalid use of model without a size[] element" << std::endl;
+
+       scene::IAnimatedMesh *mesh = m_client->getMesh(meshstr);
+
+       if (!mesh) {
+               errorstream << "Invalid model element: Unable to load mesh:"
+                               << std::endl << "\t" << meshstr << std::endl;
                return;
        }
 
-       std::string type = trim(parts[0]);
-       std::string description = trim(parts[1]);
+       FieldSpec spec(
+               name,
+               L"",
+               L"",
+               258 + m_fields.size()
+       );
+
+       core::rect<s32> rect(pos, pos + geom);
+
+       GUIScene *e = new GUIScene(Environment, m_client->getSceneManager(),
+                       data->current_parent, rect, spec.fid);
+
+       auto meshnode = e->setMesh(mesh);
+
+       for (u32 i = 0; i < textures.size() && i < meshnode->getMaterialCount(); ++i)
+               e->setTexture(i, m_tsrc->getTexture(unescape_string(textures[i])));
+
+       if (vec_rot.size() >= 2)
+               e->setRotation(v2f(stof(vec_rot[0]), stof(vec_rot[1])));
+
+       e->enableContinuousRotation(inf_rotation);
+       e->enableMouseControl(mousectrl);
+
+       s32 frame_loop_begin = 0;
+       s32 frame_loop_end = 0x7FFFFFFF;
+
+       if (frame_loop.size() == 2) {
+           frame_loop_begin = stoi(frame_loop[0]);
+           frame_loop_end = stoi(frame_loop[1]);
+       }
+
+       e->setFrameLoop(frame_loop_begin, frame_loop_end);
+       e->setAnimationSpeed(stof(speed));
+
+       auto style = getStyleForElement("model", spec.fname);
+       e->setStyles(style);
+       e->drop();
+
+       m_fields.push_back(spec);
+}
+
+void GUIFormSpecMenu::removeAll()
+{
+       // Remove children
+       removeAllChildren();
+       removeTooltip();
+
+       for (auto &table_it : m_tables)
+               table_it.second->drop();
+       for (auto &inventorylist_it : m_inventorylists)
+               inventorylist_it->drop();
+       for (auto &checkbox_it : m_checkboxes)
+               checkbox_it.second->drop();
+       for (auto &scrollbar_it : m_scrollbars)
+               scrollbar_it.second->drop();
+       for (auto &tooltip_rect_it : m_tooltip_rects)
+               tooltip_rect_it.first->drop();
+       for (auto &clickthrough_it : m_clickthrough_elements)
+               clickthrough_it->drop();
+       for (auto &scroll_container_it : m_scroll_containers)
+               scroll_container_it.second->drop();
+}
+
+void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
+{
+       //some prechecks
+       if (element.empty())
+               return;
+
+       if (parseVersionDirect(element))
+               return;
+
+       size_t pos = element.find('[');
+       if (pos == std::string::npos)
+               return;
+
+       std::string type = trim(element.substr(0, pos));
+       std::string description = element.substr(pos+1);
 
        if (type == "container") {
                parseContainer(data, description);
@@ -2223,6 +2859,11 @@ void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
                return;
        }
 
+       if (type == "animated_image") {
+               parseAnimatedImage(data, description);
+               return;
+       }
+
        if (type == "item_image") {
                parseItemImage(data, description);
                return;
@@ -2278,6 +2919,11 @@ void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
                return;
        }
 
+       if (type == "hypertext") {
+               parseHyperText(data,description);
+               return;
+       }
+
        if (type == "label") {
                parseLabel(data,description);
                return;
@@ -2333,13 +2979,38 @@ void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
                return;
        }
 
-       if (type == "style") {
-               parseStyle(data, description, false);
+       if (type == "style") {
+               parseStyle(data, description, false);
+               return;
+       }
+
+       if (type == "style_type") {
+               parseStyle(data, description, true);
+               return;
+       }
+
+       if (type == "scrollbaroptions") {
+               parseScrollBarOptions(data, description);
+               return;
+       }
+
+       if (type == "scroll_container") {
+               parseScrollContainer(data, description);
+               return;
+       }
+
+       if (type == "scroll_container_end") {
+               parseScrollContainerEnd(data);
+               return;
+       }
+
+       if (type == "set_focus") {
+               parseSetFocus(description);
                return;
        }
 
-       if (type == "style_type") {
-               parseStyle(data, description, true);
+       if (type == "model") {
+               parseModel(data, description);
                return;
        }
 
@@ -2350,74 +3021,76 @@ void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
 
 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
 {
-       /* useless to regenerate without a screensize */
+       // Useless to regenerate without a screensize
        if ((screensize.X <= 0) || (screensize.Y <= 0)) {
                return;
        }
 
        parserData mydata;
 
-       //preserve tables
-       for (auto &m_table : m_tables) {
-               std::string tablename = m_table.first.fname;
-               GUITable *table = m_table.second;
-               mydata.table_dyndata[tablename] = table->getDynamicData();
-       }
-
-       //set focus
-       if (!m_focused_element.empty())
-               mydata.focused_fieldname = m_focused_element;
-
-       //preserve focus
-       gui::IGUIElement *focused_element = Environment->getFocus();
-       if (focused_element && focused_element->getParent() == this) {
-               s32 focused_id = focused_element->getID();
-               if (focused_id > 257) {
-                       for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
-                               if (field.fid == focused_id) {
-                                       mydata.focused_fieldname = field.fname;
-                                       break;
+       // Preserve stuff only on same form, not on a new form.
+       if (m_text_dst->m_formname == m_last_formname) {
+               // Preserve tables/textlists
+               for (auto &m_table : m_tables) {
+                       std::string tablename = m_table.first.fname;
+                       GUITable *table = m_table.second;
+                       mydata.table_dyndata[tablename] = table->getDynamicData();
+               }
+
+               // Preserve focus
+               gui::IGUIElement *focused_element = Environment->getFocus();
+               if (focused_element && focused_element->getParent() == this) {
+                       s32 focused_id = focused_element->getID();
+                       if (focused_id > 257) {
+                               for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
+                                       if (field.fid == focused_id) {
+                                               m_focused_element = field.fname;
+                                               break;
+                                       }
                                }
                        }
                }
+       } else {
+               // Don't keep old focus value
+               m_focused_element = nullopt;
        }
 
-       // Remove children
-       removeChildren();
-
-       for (auto &table_it : m_tables) {
-               table_it.second->drop();
-       }
+       removeAll();
 
-       mydata.size= v2s32(100,100);
+       mydata.size = v2s32(100, 100);
        mydata.screensize = screensize;
        mydata.offset = v2f32(0.5f, 0.5f);
        mydata.anchor = v2f32(0.5f, 0.5f);
+       mydata.padding = v2f32(0.05f, 0.05f);
+       mydata.simple_field_count = 0;
 
        // Base position of contents of form
        mydata.basepos = getBasePos();
 
-       /* Convert m_init_draw_spec to m_inventorylists */
+       // the parent for the parsed elements
+       mydata.current_parent = this;
 
        m_inventorylists.clear();
-       m_images.clear();
-       m_backgrounds.clear();
-       m_itemimages.clear();
        m_tables.clear();
        m_checkboxes.clear();
        m_scrollbars.clear();
        m_fields.clear();
-       m_boxes.clear();
        m_tooltips.clear();
        m_tooltip_rects.clear();
        m_inventory_rings.clear();
-       m_static_texts.clear();
        m_dropdowns.clear();
+       m_scroll_containers.clear();
        theme_by_name.clear();
        theme_by_type.clear();
+       m_clickthrough_elements.clear();
+       field_close_on_enter.clear();
+       m_dropdown_index_event.clear();
 
+       m_bgnonfullscreen = true;
        m_bgfullscreen = false;
 
+       m_formspec_version = 1;
+
        {
                v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
                m_bgcolor = video::SColor(
@@ -2438,15 +3111,9 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                );
        }
 
-       m_slotbg_n = video::SColor(255,128,128,128);
-       m_slotbg_h = video::SColor(255,192,192,192);
-
        m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
        m_default_tooltip_color = video::SColor(255,255,255,255);
 
-       m_slotbordercolor = video::SColor(200,0,0,0);
-       m_slotborder = false;
-
        // Add tooltip
        {
                assert(!m_tooltip_element);
@@ -2496,7 +3163,14 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                }
        }
 
-       /* "no_prepend" element is always after "position" (or  "size" element) if it used */
+       /* "padding" element is always after "anchor" and previous if it is used */
+       for (; i < elements.size(); i++) {
+               if (!parsePaddingDirect(&mydata, elements[i])) {
+                       break;
+               }
+       }
+
+       /* "no_prepend" element is always after "padding" and previous if it used */
        bool enable_prepends = true;
        for (; i < elements.size(); i++) {
                if (elements[i].empty())
@@ -2543,8 +3217,8 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                        offset = v2s32(0,0);
                }
 
-               double gui_scaling = g_settings->getFloat("gui_scaling");
-               double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
+               const double gui_scaling = g_settings->getFloat("gui_scaling", 0.5f, 42.0f);
+               const double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
 
                double use_imgsize;
                if (m_lock) {
@@ -2557,42 +3231,42 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                        // and default scaling (1.00).
                        use_imgsize = 0.5555 * screen_dpi * gui_scaling;
                } else {
-                       // In variable-size mode, we prefer to make the
-                       // inventory image size 1/15 of screen height,
-                       // multiplied by the gui_scaling config parameter.
-                       // If the preferred size won't fit the whole
-                       // form on the screen, either horizontally or
-                       // vertically, then we scale it down to fit.
-                       // (The magic numbers in the computation of what
-                       // fits arise from the scaling factors in the
-                       // following stanza, including the form border,
-                       // help text space, and 0.1 inventory slot spare.)
-                       // However, a minimum size is also set, that
-                       // the image size can't be less than 0.3 inch
-                       // multiplied by gui_scaling, even if this means
-                       // the form doesn't fit the screen.
-#ifdef __ANDROID__
-                       // For mobile devices these magic numbers are
-                       // different and forms should always use the
-                       // maximum screen space available.
-                       double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
-                       double fitx_imgsize = mydata.screensize.X /
-                               ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
-                       double fity_imgsize = mydata.screensize.Y /
-                               ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
-                       use_imgsize = MYMIN(prefer_imgsize,
-                                       MYMIN(fitx_imgsize, fity_imgsize));
+                       // Variables for the maximum imgsize that can fit in the screen.
+                       double fitx_imgsize;
+                       double fity_imgsize;
+
+                       v2f padded_screensize(
+                               mydata.screensize.X * (1.0f - mydata.padding.X * 2.0f),
+                               mydata.screensize.Y * (1.0f - mydata.padding.Y * 2.0f)
+                       );
+
+                       if (mydata.real_coordinates) {
+                               fitx_imgsize = padded_screensize.X / mydata.invsize.X;
+                               fity_imgsize = padded_screensize.Y / mydata.invsize.Y;
+                       } else {
+                               // The maximum imgsize in the old coordinate system also needs to
+                               // factor in padding and spacing along with 0.1 inventory slot spare
+                               // and help text space, hence the magic numbers.
+                               fitx_imgsize = padded_screensize.X /
+                                               ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
+                               fity_imgsize = padded_screensize.Y /
+                                               ((15.0 / 13.0) * (0.85 + mydata.invsize.Y));
+                       }
+
+                       s32 min_screen_dim = std::min(padded_screensize.X, padded_screensize.Y);
+
+#ifdef HAVE_TOUCHSCREENGUI
+                       // In Android, the preferred imgsize should be larger to accommodate the
+                       // smaller screensize.
+                       double prefer_imgsize = min_screen_dim / 10 * gui_scaling;
 #else
-                       double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
-                       double fitx_imgsize = mydata.screensize.X /
-                               ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
-                       double fity_imgsize = mydata.screensize.Y /
-                               ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
-                       double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
-                       double min_imgsize = 0.3 * screen_dpi * gui_scaling;
-                       use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
-                               MYMIN(fitx_imgsize, fity_imgsize)));
+                       // Desktop computers have more space, so try to fit 15 coordinates.
+                       double prefer_imgsize = min_screen_dim / 15 * gui_scaling;
 #endif
+                       // Try to use the preferred imgsize, but if that's bigger than the maximum
+                       // size, use the maximum size.
+                       use_imgsize = std::min(prefer_imgsize,
+                                       std::min(fitx_imgsize, fity_imgsize));
                }
 
                // Everything else is scaled in proportion to the
@@ -2650,8 +3324,20 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
        gui::IGUIFont *old_font = skin->getFont();
        skin->setFont(m_font);
 
+       // Add a new element that will hold all the background elements as its children.
+       // Because it is the first added element, all backgrounds will be behind all
+       // the other elements.
+       // (We use an arbitrarily big rect. The actual size is determined later by
+       // clipping to `this`.)
+       core::rect<s32> background_parent_rect(0, 0, 100000, 100000);
+       mydata.background_parent.reset(new gui::IGUIElement(EGUIET_ELEMENT, Environment,
+                       this, -1, background_parent_rect));
+
        pos_offset = v2f32();
 
+       // used for formspec versions < 3
+       std::list<IGUIElement *>::iterator legacy_sort_start = std::prev(Children.end()); // last element
+
        if (enable_prepends) {
                // Backup the coordinates so that prepends can use the coordinates of choice.
                bool rc_backup = mydata.real_coordinates;
@@ -2662,6 +3348,14 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                for (const auto &element : prepend_elements)
                        parseElement(&mydata, element);
 
+               // legacy sorting for formspec versions < 3
+               if (m_formspec_version >= 3)
+                       // prepends do not need to be reordered
+                       legacy_sort_start = std::prev(Children.end()); // last element
+               else if (version_backup >= 3)
+                       // only prepends elements have to be reordered
+                       legacySortElements(legacy_sort_start);
+
                m_formspec_version = version_backup;
                mydata.real_coordinates = rc_backup; // Restore coordinates
        }
@@ -2670,47 +3364,109 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
                parseElement(&mydata, elements[i]);
        }
 
-       if (!container_stack.empty()) {
+       if (mydata.current_parent != this) {
+               errorstream << "Invalid formspec string: scroll_container was never closed!"
+                       << std::endl;
+       } else if (!container_stack.empty()) {
                errorstream << "Invalid formspec string: container was never closed!"
                        << std::endl;
        }
 
+       // get the scrollbar elements for scroll_containers
+       for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
+               for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
+                       if (c.first == b.first.fname) {
+                               c.second->setScrollBar(b.second);
+                               break;
+                       }
+               }
+       }
+
        // If there are fields without explicit size[], add a "Proceed"
        // button and adjust size to fit all the fields.
-       if (!m_fields.empty() && !mydata.explicit_size) {
+       if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
                mydata.rect = core::rect<s32>(
-                               mydata.screensize.X/2 - 580/2,
-                               mydata.screensize.Y/2 - 300/2,
-                               mydata.screensize.X/2 + 580/2,
-                               mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
+                               mydata.screensize.X / 2 - 580 / 2,
+                               mydata.screensize.Y / 2 - 300 / 2,
+                               mydata.screensize.X / 2 + 580 / 2,
+                               mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
                );
+
                DesiredRect = mydata.rect;
                recalculateAbsolutePosition(false);
                mydata.basepos = getBasePos();
 
                {
                        v2s32 pos = mydata.basepos;
-                       pos.Y = ((m_fields.size()+2)*60);
+                       pos.Y = (mydata.simple_field_count + 2) * 60;
 
                        v2s32 size = DesiredRect.getSize();
-                       mydata.rect =
-                                       core::rect<s32>(size.X/2-70, pos.Y,
-                                                       (size.X/2-70)+140, pos.Y + (m_btn_height*2));
+                       mydata.rect = core::rect<s32>(
+                                       size.X / 2 - 70,       pos.Y,
+                                       size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
+                       );
                        const wchar_t *text = wgettext("Proceed");
-                       Environment->addButton(mydata.rect, this, 257, text);
+                       GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
                        delete[] text;
                }
-
        }
 
-       //set initial focus if parser didn't set it
-       focused_element = Environment->getFocus();
+       // Set initial focus if parser didn't set it
+       gui::IGUIElement *focused_element = Environment->getFocus();
        if (!focused_element
                        || !isMyChild(focused_element)
                        || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
                setInitialFocus();
 
        skin->setFont(old_font);
+
+       // legacy sorting
+       if (m_formspec_version < 3)
+               legacySortElements(legacy_sort_start);
+
+       // Formname and regeneration setting
+       if (!m_is_form_regenerated) {
+               // Only set previous form name if we purposefully showed a new formspec
+               m_last_formname = m_text_dst->m_formname;
+               m_is_form_regenerated = true;
+       }
+}
+
+void GUIFormSpecMenu::legacySortElements(std::list<IGUIElement *>::iterator from)
+{
+       /*
+               Draw order for formspec_version <= 2:
+               -3  bgcolor
+               -2  background
+               -1  box
+               0   All other elements
+               1   image
+               2   item_image, item_image_button
+               3   list
+               4   label
+       */
+
+       if (from == Children.end())
+               from = Children.begin();
+       else
+               ++from;
+
+       std::list<IGUIElement *>::iterator to = Children.end();
+       // 1: Copy into a sortable container
+       std::vector<IGUIElement *> elements(from, to);
+
+       // 2: Sort the container
+       std::stable_sort(elements.begin(), elements.end(),
+                       [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
+               // TODO: getSpecByID is a linear search. It should made O(1), or cached here.
+               const FieldSpec *spec_a = getSpecByID(a->getID());
+               const FieldSpec *spec_b = getSpecByID(b->getID());
+               return spec_a && spec_b &&
+                       spec_a->priority < spec_b->priority;
+       });
+
+       // 3: Re-assign the pointers
+       reorderChildren(from, to, elements);
 }
 
 #ifdef __ANDROID__
@@ -2719,162 +3475,39 @@ bool GUIFormSpecMenu::getAndroidUIInput()
        if (!hasAndroidUIInput())
                return false;
 
+       // still waiting
+       if (porting::getInputDialogState() == -1)
+               return true;
+
        std::string fieldname = m_jni_field_name;
        m_jni_field_name.clear();
 
-       for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
-                       iter != m_fields.end(); ++iter) {
-
-               if (iter->fname != fieldname) {
+       for (const FieldSpec &field : m_fields) {
+               if (field.fname != fieldname)
                        continue;
-               }
-               IGUIElement* tochange = getElementFromId(iter->fid);
 
-               if (tochange == 0) {
-                       return false;
-               }
+               IGUIElement *element = getElementFromId(field.fid, true);
 
-               if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
+               if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
                        return false;
-               }
 
                std::string text = porting::getInputDialogValue();
-
-               ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str());
+               ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
        }
        return false;
 }
 #endif
 
-GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
-{
-       core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
-
-       for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
-               for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
-                       s32 item_i = i + s.start_item_i;
-
-                       s32 x;
-                       s32 y;
-                       if (s.real_coordinates) {
-                               x = (i%s.geom.X) * (imgsize.X * 1.25);
-                               y = (i/s.geom.X) * (imgsize.Y * 1.25);
-                       } else {
-                               x = (i%s.geom.X) * spacing.X;
-                               y = (i/s.geom.X) * spacing.Y;
-                       }
-                       v2s32 p0(x,y);
-                       core::rect<s32> rect = imgrect + s.pos + p0;
-                       if(rect.isPointInside(p))
-                       {
-                               return ItemSpec(s.inventoryloc, s.listname, item_i);
-                       }
-               }
-       }
-
-       return ItemSpec(InventoryLocation(), "", -1);
-}
-
-void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer,
-               bool &item_hovered)
+GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
 {
-       video::IVideoDriver* driver = Environment->getVideoDriver();
-
-       Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
-       if(!inv){
-               warningstream<<"GUIFormSpecMenu::drawList(): "
-                               <<"The inventory location "
-                               <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
-                               <<std::endl;
-               return;
-       }
-       InventoryList *ilist = inv->getList(s.listname);
-       if(!ilist){
-               warningstream<<"GUIFormSpecMenu::drawList(): "
-                               <<"The inventory list \""<<s.listname<<"\" @ \""
-                               <<s.inventoryloc.dump()<<"\" doesn't exist"
-                               <<std::endl;
-               return;
+       for (const GUIInventoryList *e : m_inventorylists) {
+               s32 item_index = e->getItemIndexAtPos(p);
+               if (item_index != -1)
+                       return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
+                                       item_index, e->getSlotSize());
        }
 
-       core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
-
-       for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) {
-               s32 item_i = i + s.start_item_i;
-               if (item_i >= (s32)ilist->getSize())
-                       break;
-
-               s32 x;
-               s32 y;
-               if (s.real_coordinates) {
-                       x = (i%s.geom.X) * (imgsize.X * 1.25);
-                       y = (i/s.geom.X) * (imgsize.Y * 1.25);
-               } else {
-                       x = (i%s.geom.X) * spacing.X;
-                       y = (i/s.geom.X) * spacing.Y;
-               }
-               v2s32 p(x,y);
-               core::rect<s32> rect = imgrect + s.pos + p;
-               ItemStack item = ilist->getItem(item_i);
-
-               bool selected = m_selected_item
-                       && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
-                       && m_selected_item->listname == s.listname
-                       && m_selected_item->i == item_i;
-               bool hovering = rect.isPointInside(m_pointer);
-               ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
-                       (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
-
-               if (layer == 0) {
-                       if (hovering) {
-                               item_hovered = true;
-                               driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
-                       } else {
-                               driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
-                       }
-               }
-
-               //Draw inv slot borders
-               if (m_slotborder) {
-                       s32 x1 = rect.UpperLeftCorner.X;
-                       s32 y1 = rect.UpperLeftCorner.Y;
-                       s32 x2 = rect.LowerRightCorner.X;
-                       s32 y2 = rect.LowerRightCorner.Y;
-                       s32 border = 1;
-                       driver->draw2DRectangle(m_slotbordercolor,
-                               core::rect<s32>(v2s32(x1 - border, y1 - border),
-                                                               v2s32(x2 + border, y1)), NULL);
-                       driver->draw2DRectangle(m_slotbordercolor,
-                               core::rect<s32>(v2s32(x1 - border, y2),
-                                                               v2s32(x2 + border, y2 + border)), NULL);
-                       driver->draw2DRectangle(m_slotbordercolor,
-                               core::rect<s32>(v2s32(x1 - border, y1),
-                                                               v2s32(x1, y2)), NULL);
-                       driver->draw2DRectangle(m_slotbordercolor,
-                               core::rect<s32>(v2s32(x2, y1),
-                                                               v2s32(x2 + border, y2)), NULL);
-               }
-
-               if (layer == 1) {
-                       if (selected)
-                               item.takeItem(m_selected_amount);
-
-                       if (!item.empty()) {
-                               // Draw item stack
-                               drawItemStack(driver, m_font, item,
-                                       rect, &AbsoluteClippingRect, m_client,
-                                       rotation_kind);
-                               // Draw tooltip
-                               if (hovering && !m_selected_item) {
-                                       std::string tooltip = item.getDescription(m_client->idef());
-                                       if (m_tooltip_append_itemname)
-                                               tooltip += "\n[" + item.name + "]";
-                                       showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
-                                                       m_default_tooltip_bgcolor);
-                               }
-                       }
-               }
-       }
+       return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1, {0,0});
 }
 
 void GUIFormSpecMenu::drawSelectedItem()
@@ -2882,9 +3515,10 @@ void GUIFormSpecMenu::drawSelectedItem()
        video::IVideoDriver* driver = Environment->getVideoDriver();
 
        if (!m_selected_item) {
+               // reset rotation time
                drawItemStack(driver, m_font, ItemStack(),
-                       core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
-                       NULL, m_client, IT_ROT_DRAGGED);
+                               core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
+                               m_client, IT_ROT_DRAGGED);
                return;
        }
 
@@ -2895,7 +3529,8 @@ void GUIFormSpecMenu::drawSelectedItem()
        ItemStack stack = list->getItem(m_selected_item->i);
        stack.count = m_selected_amount;
 
-       core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
+       v2s32 slotsize = m_selected_item->slotsize;
+       core::rect<s32> imgrect(0, 0, slotsize.X, slotsize.Y);
        core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
        rect.constrainTo(driver->getViewPort());
        drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
@@ -2907,6 +3542,7 @@ void GUIFormSpecMenu::drawMenu()
                const std::string &newform = m_form_src->getForm();
                if (newform != m_formspec_string) {
                        m_formspec_string = newform;
+                       m_is_form_regenerated = false;
                        regenerateGui(m_screensize_old);
                }
        }
@@ -2916,21 +3552,31 @@ void GUIFormSpecMenu::drawMenu()
        gui::IGUIFont *old_font = skin->getFont();
        skin->setFont(m_font);
 
+       m_hovered_item_tooltips.clear();
+
        updateSelectedItem();
 
        video::IVideoDriver* driver = Environment->getVideoDriver();
 
+       /*
+               Draw background color
+       */
        v2u32 screenSize = driver->getScreenSize();
        core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
 
        if (m_bgfullscreen)
                driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
-       driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
+       if (m_bgnonfullscreen)
+               driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
 
+       /*
+               Draw rect_mode tooltip
+       */
        m_tooltip_element->setVisible(false);
 
        for (const auto &pair : m_tooltip_rects) {
-               if (pair.first.isPointInside(m_pointer)) {
+               const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
+               if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
                        const std::wstring &text = pair.second.tooltip;
                        if (!text.empty()) {
                                showTooltip(text, pair.second.color, pair.second.bgcolor);
@@ -2939,138 +3585,30 @@ void GUIFormSpecMenu::drawMenu()
                }
        }
 
-       /*
-               Draw backgrounds
-       */
-       for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_backgrounds) {
-               video::ITexture *texture = m_tsrc->getTexture(spec.name);
-
-               if (texture != 0) {
-                       // Image size on screen
-                       core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
-                       // Image rectangle on screen
-                       core::rect<s32> rect = imgrect + spec.pos;
-                       // Middle rect for 9-slicing
-                       core::rect<s32> middle = spec.middle;
-
-                       if (spec.clip) {
-                               core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
-                               rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
-                                                                       AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
-                                                                       AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
-                                                                       AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
-                       }
-
-                       if (middle.getArea() == 0) {
-                               const video::SColor color(255, 255, 255, 255);
-                               const video::SColor colors[] = {color, color, color, color};
-                               draw2DImageFilterScaled(driver, texture, rect,
-                                               core::rect<s32>(core::position2d<s32>(0, 0),
-                                                               core::dimension2di(texture->getOriginalSize())),
-                                               NULL/*&AbsoluteClippingRect*/, colors, true);
-                       } else {
-                               // `-x` is interpreted as `w - x`
-                               if (middle.LowerRightCorner.X < 0) {
-                                       middle.LowerRightCorner.X += texture->getOriginalSize().Width;
-                               }
-                               if (middle.LowerRightCorner.Y < 0) {
-                                       middle.LowerRightCorner.Y += texture->getOriginalSize().Height;
-                               }
-                               draw2DImage9Slice(driver, texture, rect, middle);
-                       }
-               } else {
-                       errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
-                       errorstream << "\t" << spec.name << std::endl;
-               }
-       }
-
-       /*
-               Draw Boxes
-       */
-       for (const GUIFormSpecMenu::BoxDrawSpec &spec : m_boxes) {
-               irr::video::SColor todraw = spec.color;
-
-               core::rect<s32> rect(spec.pos.X,spec.pos.Y,
-                                                       spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
-
-               driver->draw2DRectangle(todraw, rect, 0);
-       }
-
-       /*
-               Call base class
-       */
-       gui::IGUIElement::draw();
+       // Some elements are only visible while being drawn
+       for (gui::IGUIElement *e : m_clickthrough_elements)
+               e->setVisible(true);
 
        /*
-               Draw images
+               This is where all the drawing happens.
        */
-       for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_images) {
-               video::ITexture *texture = m_tsrc->getTexture(spec.name);
-
-               if (texture != 0) {
-                       const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
-                       // Image size on screen
-                       core::rect<s32> imgrect;
-
-                       if (spec.scale)
-                               imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
-                       else {
-
-                               imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
-                       }
-                       // Image rectangle on screen
-                       core::rect<s32> rect = imgrect + spec.pos;
-                       const video::SColor color(255,255,255,255);
-                       const video::SColor colors[] = {color,color,color,color};
-                       draw2DImageFilterScaled(driver, texture, rect,
-                               core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
-                               NULL/*&AbsoluteClippingRect*/, colors, true);
-               }
-               else {
-                       errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
-                       errorstream << "\t" << spec.name << std::endl;
-               }
-       }
+       for (auto child : Children)
+               if (child->isNotClipped() ||
+                               AbsoluteClippingRect.isRectCollided(
+                                               child->getAbsolutePosition()))
+                       child->draw();
 
-       /*
-               Draw item images
-       */
-       for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_itemimages) {
-               if (m_client == 0)
-                       break;
+       for (gui::IGUIElement *e : m_clickthrough_elements)
+               e->setVisible(false);
 
-               IItemDefManager *idef = m_client->idef();
-               ItemStack item;
-               item.deSerialize(spec.item_name, idef);
-               core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
-               // Viewport rectangle on screen
-               core::rect<s32> rect = imgrect + spec.pos;
-               if (spec.parent_button && spec.parent_button->isPressed()) {
-#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
-                       rect += core::dimension2d<s32>(
-                               0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
-#else
-                       rect += core::dimension2d<s32>(
-                               skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
-                               skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
-#endif
-               }
-               drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect,
-                               m_client, IT_ROT_NONE);
+       // Draw hovered item tooltips
+       for (const std::string &tooltip : m_hovered_item_tooltips) {
+               showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
+                               m_default_tooltip_bgcolor);
        }
 
-       /*
-               Draw items
-               Layer 0: Item slot rectangles
-               Layer 1: Item images; prepare tooltip
-       */
-       bool item_hovered = false;
-       for (int layer = 0; layer < 2; layer++) {
-               for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
-                       drawList(spec, layer, item_hovered);
-               }
-       }
-       if (!item_hovered) {
+       if (m_hovered_item_tooltips.empty()) {
+               // reset rotation time
                drawItemStack(driver, m_font, ItemStack(),
                        core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
                        NULL, m_client, IT_ROT_HOVERED);
@@ -3082,34 +3620,32 @@ void GUIFormSpecMenu::drawMenu()
 #endif
 
        /*
-               Draw static text elements
-       */
-       for (const GUIFormSpecMenu::StaticTextSpec &spec : m_static_texts) {
-               core::rect<s32> rect = spec.rect;
-               if (spec.parent_button && spec.parent_button->isPressed()) {
-#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
-                       rect += core::dimension2d<s32>(
-                               0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
-#else
-                       // Use image offset instead of text's because its a bit smaller
-                       // and fits better, also TEXT_OFFSET_X is always 0
-                       rect += core::dimension2d<s32>(
-                               skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
-                               skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
-#endif
-               }
-               video::SColor color(255, 255, 255, 255);
-               m_font->draw(spec.text.c_str(), rect, color, true, true, &rect);
-       }
-
-       /*
-               Draw fields/buttons tooltips
+               Draw fields/buttons tooltips and update the mouse cursor
        */
        gui::IGUIElement *hovered =
                        Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
 
-       if (hovered != NULL) {
-               s32 id = hovered->getID();
+#ifndef HAVE_TOUCHSCREENGUI
+       gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
+                       getCursorControl();
+       gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
+#endif
+       bool hovered_element_found = false;
+
+       if (hovered) {
+               if (m_show_debug) {
+                       core::rect<s32> rect = hovered->getAbsoluteClippingRect();
+                       driver->draw2DRectangle(0x22FFFF00, rect, &rect);
+               }
+
+               // find the formspec-element of the hovered IGUIElement (a parent)
+               s32 id;
+               for (gui::IGUIElement *hovered_fselem = hovered; hovered_fselem;
+                               hovered_fselem = hovered_fselem->getParent()) {
+                       id = hovered_fselem->getID();
+                       if (id != -1)
+                               break;
+               }
 
                u64 delta = 0;
                if (id == -1) {
@@ -3123,23 +3659,41 @@ void GUIFormSpecMenu::drawMenu()
                        }
                }
 
-               // Find and update the current tooltip
-               if (id != -1 && delta >= m_tooltip_show_delay) {
+               // Find and update the current tooltip and cursor icon
+               if (id != -1) {
                        for (const FieldSpec &field : m_fields) {
 
                                if (field.fid != id)
                                        continue;
 
-                               const std::wstring &text = m_tooltips[field.fname].tooltip;
-                               if (!text.empty())
-                                       showTooltip(text, m_tooltips[field.fname].color,
-                                               m_tooltips[field.fname].bgcolor);
+                               if (delta >= m_tooltip_show_delay) {
+                                       const std::wstring &text = m_tooltips[field.fname].tooltip;
+                                       if (!text.empty())
+                                               showTooltip(text, m_tooltips[field.fname].color,
+                                                       m_tooltips[field.fname].bgcolor);
+                               }
+
+#ifndef HAVE_TOUCHSCREENGUI
+                               if (field.ftype != f_HyperText && // Handled directly in guiHyperText
+                                               current_cursor_icon != field.fcursor_icon)
+                                       cursor_control->setActiveIcon(field.fcursor_icon);
+#endif
+
+                               hovered_element_found = true;
 
                                break;
                        }
                }
        }
 
+       if (!hovered_element_found) {
+               // no element is hovered
+#ifndef HAVE_TOUCHSCREENGUI
+               if (current_cursor_icon != ECI_NORMAL)
+                       cursor_control->setActiveIcon(ECI_NORMAL);
+#endif
+       }
+
        m_tooltip_element->draw();
 
        /*
@@ -3154,27 +3708,29 @@ void GUIFormSpecMenu::drawMenu()
 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
        const irr::video::SColor &color, const irr::video::SColor &bgcolor)
 {
-       const std::wstring ntext = translate_string(text);
-       m_tooltip_element->setOverrideColor(color);
-       m_tooltip_element->setBackgroundColor(bgcolor);
-       setStaticText(m_tooltip_element, ntext.c_str());
+       EnrichedString ntext(text);
+       ntext.setDefaultColor(color);
+       if (!ntext.hasBackground())
+               ntext.setBackground(bgcolor);
+
+       setStaticText(m_tooltip_element, ntext);
 
        // Tooltip size and offset
        s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
-#if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
-       std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
-       s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
-#else
        s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
-#endif
+
        v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
        int tooltip_offset_x = m_btn_height;
        int tooltip_offset_y = m_btn_height;
-#ifdef __ANDROID__
+#ifdef HAVE_TOUCHSCREENGUI
        tooltip_offset_x *= 3;
        tooltip_offset_y  = 0;
        if (m_pointer.X > (s32)screenSize.X / 2)
                tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
+
+       // Hide tooltip after ETIE_LEFT_UP
+       if (m_pointer.X == 0)
+               return;
 #endif
 
        // Calculate and set the tooltip position
@@ -3203,11 +3759,11 @@ void GUIFormSpecMenu::updateSelectedItem()
 
        // If craftresult is nonempty and nothing else is selected, select it now.
        if (!m_selected_item) {
-               for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
-                       if (s.listname != "craftpreview")
+               for (const GUIInventoryList *e : m_inventorylists) {
+                       if (e->getListname() != "craftpreview")
                                continue;
 
-                       Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
+                       Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
                        if (!inv)
                                continue;
 
@@ -3221,10 +3777,11 @@ void GUIFormSpecMenu::updateSelectedItem()
                                continue;
 
                        // Grab selected item from the crafting result list
-                       m_selected_item = new ItemSpec;
-                       m_selected_item->inventoryloc = s.inventoryloc;
+                       m_selected_item = new GUIInventoryList::ItemSpec;
+                       m_selected_item->inventoryloc = e->getInventoryloc();
                        m_selected_item->listname = "craftresult";
                        m_selected_item->i = 0;
+                       m_selected_item->slotsize = e->getSlotSize();
                        m_selected_amount = item.count;
                        m_selected_dragging = false;
                        break;
@@ -3243,16 +3800,12 @@ ItemStack GUIFormSpecMenu::verifySelectedItem()
        // If the selected stack has become smaller, adjust m_selected_amount.
        // Return the selected stack.
 
-       if(m_selected_item)
-       {
-               if(m_selected_item->isValid())
-               {
+       if (m_selected_item) {
+               if (m_selected_item->isValid()) {
                        Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
-                       if(inv)
-                       {
+                       if (inv) {
                                InventoryList *list = inv->getList(m_selected_item->listname);
-                               if(list && (u32) m_selected_item->i < list->getSize())
-                               {
+                               if (list && (u32) m_selected_item->i < list->getSize()) {
                                        ItemStack stack = list->getItem(m_selected_item->i);
                                        if (!m_selected_swap.empty()) {
                                                if (m_selected_swap.name == stack.name &&
@@ -3270,14 +3823,14 @@ ItemStack GUIFormSpecMenu::verifySelectedItem()
 
                // selection was not valid
                delete m_selected_item;
-               m_selected_item = NULL;
+               m_selected_item = nullptr;
                m_selected_amount = 0;
                m_selected_dragging = false;
        }
        return ItemStack();
 }
 
-void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
+void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
 {
        if(m_text_dst)
        {
@@ -3310,7 +3863,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
 
                if (!current_field_enter_pending.empty()) {
                        fields["key_enter_field"] = current_field_enter_pending;
-                       current_field_enter_pending = "";
+                       current_field_enter_pending.clear();
                }
 
                if (current_keys_pending.key_escape) {
@@ -3319,7 +3872,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
                }
 
                for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
-                       if(s.send) {
+                       if (s.send) {
                                std::string name = s.fname;
                                if (s.ftype == f_Button) {
                                        fields[name] = wide_to_utf8(s.flabel);
@@ -3328,44 +3881,47 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
                                        if (table) {
                                                fields[name] = table->checkEvent();
                                        }
-                               }
-                               else if(s.ftype == f_DropDown) {
-                                       // no dynamic cast possible due to some distributions shipped
-                                       // without rtti support in irrlicht
-                                       IGUIElement * element = getElementFromId(s.fid);
+                               } else if (s.ftype == f_DropDown) {
+                                       // No dynamic cast possible due to some distributions shipped
+                                       // without rtti support in Irrlicht
+                                       IGUIElement *element = getElementFromId(s.fid, true);
                                        gui::IGUIComboBox *e = NULL;
                                        if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
-                                               e = static_cast<gui::IGUIComboBox*>(element);
+                                               e = static_cast<gui::IGUIComboBox *>(element);
+                                       } else {
+                                               warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
+                                                               << "field without dropdown element" << std::endl;
+                                               continue;
                                        }
                                        s32 selected = e->getSelected();
                                        if (selected >= 0) {
-                                               std::vector<std::string> *dropdown_values =
-                                                       getDropDownValues(s.fname);
-                                               if (dropdown_values && selected < (s32)dropdown_values->size()) {
-                                                       fields[name] = (*dropdown_values)[selected];
+                                               if (m_dropdown_index_event.find(s.fname) !=
+                                                               m_dropdown_index_event.end()) {
+                                                       fields[name] = std::to_string(selected + 1);
+                                               } else {
+                                                       std::vector<std::string> *dropdown_values =
+                                                               getDropDownValues(s.fname);
+                                                       if (dropdown_values && selected < (s32)dropdown_values->size())
+                                                               fields[name] = (*dropdown_values)[selected];
                                                }
                                        }
-                               }
-                               else if (s.ftype == f_TabHeader) {
-                                       // no dynamic cast possible due to some distributions shipped
-                                       // without rttzi support in irrlicht
-                                       IGUIElement * element = getElementFromId(s.fid);
-                                       gui::IGUITabControl *e = NULL;
+                               } else if (s.ftype == f_TabHeader) {
+                                       // No dynamic cast possible due to some distributions shipped
+                                       // without rtti support in Irrlicht
+                                       IGUIElement *element = getElementFromId(s.fid, true);
+                                       gui::IGUITabControl *e = nullptr;
                                        if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
                                                e = static_cast<gui::IGUITabControl *>(element);
                                        }
 
                                        if (e != 0) {
-                                               std::stringstream ss;
-                                               ss << (e->getActiveTab() +1);
-                                               fields[name] = ss.str();
+                                               fields[name] = itos(e->getActiveTab() + 1);
                                        }
-                               }
-                               else if (s.ftype == f_CheckBox) {
-                                       // no dynamic cast possible due to some distributions shipped
-                                       // without rtti support in irrlicht
-                                       IGUIElement * element = getElementFromId(s.fid);
-                                       gui::IGUICheckBox *e = NULL;
+                               } else if (s.ftype == f_CheckBox) {
+                                       // No dynamic cast possible due to some distributions shipped
+                                       // without rtti support in Irrlicht
+                                       IGUIElement *element = getElementFromId(s.fid, true);
+                                       gui::IGUICheckBox *e = nullptr;
                                        if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
                                                e = static_cast<gui::IGUICheckBox*>(element);
                                        }
@@ -3376,31 +3932,34 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
                                                else
                                                        fields[name] = "false";
                                        }
-                               }
-                               else if (s.ftype == f_ScrollBar) {
-                                       // no dynamic cast possible due to some distributions shipped
-                                       // without rtti support in irrlicht
-                                       IGUIElement * element = getElementFromId(s.fid);
-                                       gui::IGUIScrollBar *e = NULL;
-                                       if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
-                                               e = static_cast<gui::IGUIScrollBar*>(element);
-                                       }
-
-                                       if (e != 0) {
-                                               std::stringstream os;
-                                               os << e->getPos();
+                               } else if (s.ftype == f_ScrollBar) {
+                                       // No dynamic cast possible due to some distributions shipped
+                                       // without rtti support in Irrlicht
+                                       IGUIElement *element = getElementFromId(s.fid, true);
+                                       GUIScrollBar *e = nullptr;
+                                       if (element && element->getType() == gui::EGUIET_ELEMENT)
+                                               e = static_cast<GUIScrollBar *>(element);
+
+                                       if (e) {
                                                if (s.fdefault == L"Changed")
-                                                       fields[name] = "CHG:" + os.str();
+                                                       fields[name] = "CHG:" + itos(e->getPos());
                                                else
-                                                       fields[name] = "VAL:" + os.str();
+                                                       fields[name] = "VAL:" + itos(e->getPos());
                                        }
-                               }
-                               else
-                               {
-                                       IGUIElement* e = getElementFromId(s.fid);
-                                       if(e != NULL) {
+                               } else if (s.ftype == f_AnimatedImage) {
+                                       // No dynamic cast possible due to some distributions shipped
+                                       // without rtti support in Irrlicht
+                                       IGUIElement *element = getElementFromId(s.fid, true);
+                                       GUIAnimatedImage *e = nullptr;
+                                       if (element && element->getType() == gui::EGUIET_ELEMENT)
+                                               e = static_cast<GUIAnimatedImage *>(element);
+
+                                       if (e)
+                                               fields[name] = std::to_string(e->getFrameIndex() + 1);
+                               } else {
+                                       IGUIElement *e = getElementFromId(s.fid, true);
+                                       if (e)
                                                fields[name] = wide_to_utf8(e->getText());
-                                       }
                                }
                        }
                }
@@ -3409,17 +3968,6 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
        }
 }
 
-static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
-{
-       while(tocheck != NULL) {
-               if (tocheck == parent) {
-                       return true;
-               }
-               tocheck = tocheck->getParent();
-       }
-       return false;
-}
-
 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
 {
        // The IGUITabControl renders visually using the skin's selected
@@ -3448,8 +3996,8 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
        }
 
        // Fix Esc/Return key being eaten by checkboxen and tables
-       if(event.EventType==EET_KEY_INPUT_EVENT) {
-               KeyPress kp(event.KeyInput);
+       if (event.EventType == EET_KEY_INPUT_EVENT) {
+                       KeyPress kp(event.KeyInput);
                if (kp == EscapeKey || kp == CancelKey
                                || kp == getKeySetting("keymap_inventory")
                                || event.KeyInput.Key==KEY_RETURN) {
@@ -3464,9 +4012,11 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
                        }
                }
        }
-       // Mouse wheel events: send to hovered element instead of focused
-       if(event.EventType==EET_MOUSE_INPUT_EVENT
-                       && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
+       // Mouse wheel and move events: send to hovered element instead of focused
+       if (event.EventType == EET_MOUSE_INPUT_EVENT &&
+                       (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
+                       (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
+                       event.MouseInput.ButtonStates == 0))) {
                s32 x = event.MouseInput.X;
                s32 y = event.MouseInput.Y;
                gui::IGUIElement *hovered =
@@ -3474,23 +4024,7 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
                                core::position2d<s32>(x, y));
                if (hovered && isMyChild(hovered)) {
                        hovered->OnEvent(event);
-                       return true;
-               }
-       }
-
-       if (event.EventType == EET_MOUSE_INPUT_EVENT) {
-               s32 x = event.MouseInput.X;
-               s32 y = event.MouseInput.Y;
-               gui::IGUIElement *hovered =
-                       Environment->getRootGUIElement()->getElementFromPoint(
-                               core::position2d<s32>(x, y));
-               if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
-                       m_old_tooltip_id = -1;
-               }
-               if (!isChild(hovered,this)) {
-                       if (DoubleClickDetection(event)) {
-                               return true;
-                       }
+                       return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
                }
        }
 
@@ -3516,64 +4050,6 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
        return GUIModalMenu::preprocessEvent(event);
 }
 
-/******************************************************************************/
-bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
-{
-       /* The following code is for capturing double-clicks of the mouse button
-        * and translating the double-click into an EET_KEY_INPUT_EVENT event
-        * -- which closes the form -- under some circumstances.
-        *
-        * There have been many github issues reporting this as a bug even though it
-        * was an intended feature.  For this reason, remapping the double-click as
-        * an ESC must be explicitly set when creating this class via the
-        * /p remap_dbl_click parameter of the constructor.
-        */
-
-       if (!m_remap_dbl_click)
-               return false;
-
-       if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
-               m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
-               m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
-
-               m_doubleclickdetect[1].pos  = m_pointer;
-               m_doubleclickdetect[1].time = porting::getTimeMs();
-       }
-       else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
-               u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
-               if (delta > 400) {
-                       return false;
-               }
-
-               double squaredistance =
-                               m_doubleclickdetect[0].pos
-                               .getDistanceFromSQ(m_doubleclickdetect[1].pos);
-
-               if (squaredistance > (30*30)) {
-                       return false;
-               }
-
-               SEvent* translated = new SEvent();
-               assert(translated != 0);
-               //translate doubleclick to escape
-               memset(translated, 0, sizeof(SEvent));
-               translated->EventType = irr::EET_KEY_INPUT_EVENT;
-               translated->KeyInput.Key         = KEY_ESCAPE;
-               translated->KeyInput.Control     = false;
-               translated->KeyInput.Shift       = false;
-               translated->KeyInput.PressedDown = true;
-               translated->KeyInput.Char        = 0;
-               OnEvent(*translated);
-
-               // no need to send the key up event as we're already deleted
-               // and no one else did notice this event
-               delete translated;
-               return true;
-       }
-
-       return false;
-}
-
 void GUIFormSpecMenu::tryClose()
 {
        if (m_allowclose) {
@@ -3613,6 +4089,10 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                                (kp == getKeySetting("keymap_screenshot"))) {
                        m_client->makeScreenshot();
                }
+
+               if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
+                       m_show_debug = !m_show_debug;
+
                if (event.KeyInput.PressedDown &&
                        (event.KeyInput.Key==KEY_RETURN ||
                         event.KeyInput.Key==KEY_UP ||
@@ -3658,7 +4138,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
 
                m_old_tooltip_id = -1;
                updateSelectedItem();
-               ItemSpec s = getItemAtPos(m_pointer);
+               GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
 
                Inventory *inv_selected = NULL;
                Inventory *inv_s = NULL;
@@ -3760,8 +4240,9 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                case BET_DOWN:
                        // Some mouse button has been pressed
 
-                       //infostream<<"Mouse button "<<button<<" pressed at p=("
-                       //      <<p.X<<","<<p.Y<<")"<<std::endl;
+                       //infostream << "Mouse button " << button << " pressed at p=("
+                       //      << event.MouseInput.X << "," << event.MouseInput.Y << ")"
+                       //      << std::endl;
 
                        m_selected_dragging = false;
 
@@ -3771,7 +4252,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                        } else if (!m_selected_item) {
                                if (s_count && button != BET_WHEEL_UP) {
                                        // Non-empty stack has been clicked: select or shift-move it
-                                       m_selected_item = new ItemSpec(s);
+                                       m_selected_item = new GUIInventoryList::ItemSpec(s);
 
                                        u32 count;
                                        if (button == BET_RIGHT)
@@ -3999,7 +4480,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
 
                        // if there are no items selected or the selected item
                        // belongs to craftresult list, proceed with crafting
-                       if (m_selected_item == NULL ||
+                       if (!m_selected_item ||
                                        !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
 
                                assert(inv_s);
@@ -4017,20 +4498,22 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                if (m_selected_amount == 0) {
                        m_selected_swap.clear();
                        delete m_selected_item;
-                       m_selected_item = NULL;
+                       m_selected_item = nullptr;
                        m_selected_amount = 0;
                        m_selected_dragging = false;
                }
                m_old_pointer = m_pointer;
        }
-       if (event.EventType == EET_GUI_EVENT) {
 
+       if (event.EventType == EET_GUI_EVENT) {
                if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
                                && isVisible()) {
                        // find the element that was clicked
                        for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
                                if ((s.ftype == f_TabHeader) &&
                                                (s.fid == event.GUIEvent.Caller->getID())) {
+                                       if (!s.sound.empty() && m_sound_manager)
+                                               m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
                                        s.send = true;
                                        acceptInput();
                                        s.send = false;
@@ -4051,9 +4534,9 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                                (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
                                (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
                                (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
-                       unsigned int btn_id = event.GUIEvent.Caller->getID();
+                       s32 caller_id = event.GUIEvent.Caller->getID();
 
-                       if (btn_id == 257) {
+                       if (caller_id == 257) {
                                if (m_allowclose) {
                                        acceptInput(quit_mode_accept);
                                        quitMenu();
@@ -4069,8 +4552,14 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                        for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
                                // if its a button, set the send field so
                                // lua knows which button was pressed
-                               if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
-                                               s.fid == event.GUIEvent.Caller->getID()) {
+
+                               if (caller_id != s.fid)
+                                       continue;
+
+                               if (s.ftype == f_Button || s.ftype == f_CheckBox) {
+                                       if (!s.sound.empty() && m_sound_manager)
+                                               m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
+
                                        s.send = true;
                                        if (s.is_exit) {
                                                if (m_allowclose) {
@@ -4086,14 +4575,15 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                                        s.send = false;
                                        return true;
 
-                               } else if ((s.ftype == f_DropDown) &&
-                                               (s.fid == event.GUIEvent.Caller->getID())) {
+                               } else if (s.ftype == f_DropDown) {
                                        // only send the changed dropdown
                                        for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
                                                if (s2.ftype == f_DropDown) {
                                                        s2.send = false;
                                                }
                                        }
+                                       if (!s.sound.empty() && m_sound_manager)
+                                               m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
                                        s.send = true;
                                        acceptInput(quit_mode_no);
 
@@ -4105,15 +4595,26 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                                                }
                                        }
                                        return true;
-                               } else if ((s.ftype == f_ScrollBar) &&
-                                               (s.fid == event.GUIEvent.Caller->getID())) {
+                               } else if (s.ftype == f_ScrollBar) {
                                        s.fdefault = L"Changed";
                                        acceptInput(quit_mode_no);
-                                       s.fdefault = L"";
+                                       s.fdefault.clear();
+                               } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
+                                       if (!s.sound.empty() && m_sound_manager)
+                                               m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));
+                                       s.send = true;
+                                       acceptInput();
+                                       s.send = false;
                                }
                        }
                }
 
+               if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
+                       // move scroll_containers
+                       for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
+                               c.second->onScrollEvent(event.GUIEvent.Caller);
+               }
+
                if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
                        if (event.GUIEvent.Caller->getID() > 257) {
                                bool close_on_enter = true;
@@ -4172,13 +4673,22 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
 std::string GUIFormSpecMenu::getNameByID(s32 id)
 {
        for (FieldSpec &spec : m_fields) {
-               if (spec.fid == id) {
+               if (spec.fid == id)
                        return spec.fname;
-               }
        }
        return "";
 }
 
+
+const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
+{
+       for (FieldSpec &spec : m_fields) {
+               if (spec.fid == id)
+                       return &spec;
+       }
+       return nullptr;
+}
+
 /**
  * get label of element by id
  * @param id of element
@@ -4187,32 +4697,52 @@ std::string GUIFormSpecMenu::getNameByID(s32 id)
 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
 {
        for (FieldSpec &spec : m_fields) {
-               if (spec.fid == id) {
+               if (spec.fid == id)
                        return spec.flabel;
-               }
        }
        return L"";
 }
 
-StyleSpec GUIFormSpecMenu::getStyleForElement(const std::string &type,
+StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
                const std::string &name, const std::string &parent_type) {
-       StyleSpec ret;
+       return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
+}
+
+std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
+       const std::string &type, const std::string &name, const std::string &parent_type)
+{
+       std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
+
+       auto it = theme_by_type.find("*");
+       if (it != theme_by_type.end()) {
+               for (const StyleSpec &spec : it->second)
+                       ret[(u32)spec.getState()] |= spec;
+       }
+
+       it = theme_by_name.find("*");
+       if (it != theme_by_name.end()) {
+               for (const StyleSpec &spec : it->second)
+                       ret[(u32)spec.getState()] |= spec;
+       }
 
        if (!parent_type.empty()) {
-               auto it = theme_by_type.find(parent_type);
+               it = theme_by_type.find(parent_type);
                if (it != theme_by_type.end()) {
-                       ret |= it->second;
+                       for (const StyleSpec &spec : it->second)
+                               ret[(u32)spec.getState()] |= spec;
                }
        }
 
-       auto it = theme_by_type.find(type);
+       it = theme_by_type.find(type);
        if (it != theme_by_type.end()) {
-               ret |= it->second;
+               for (const StyleSpec &spec : it->second)
+                       ret[(u32)spec.getState()] |= spec;
        }
 
        it = theme_by_name.find(name);
        if (it != theme_by_name.end()) {
-               ret |= it->second;
+               for (const StyleSpec &spec : it->second)
+                       ret[(u32)spec.getState()] |= spec;
        }
 
        return ret;