LCOV - code coverage report
Current view: top level - source/simulation2/system - ParamNode.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 210 228 92.1 %
Date: 2026-12-03 01:19:39 Functions: 19 22 86.4 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "ParamNode.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "lib/path.h"
      24             : #include "lib/utf8.h"
      25             : #include "ps/CLogger.h"
      26             : #include "ps/CStr.h"
      27             : #include "ps/CStrIntern.h"
      28             : #include "ps/Filesystem.h"
      29             : #include "ps/XMB/XMBData.h"
      30             : #include "ps/XML/Xeromyces.h"
      31             : #include "scriptinterface/Object.h"
      32             : #include "scriptinterface/Interface.h"
      33             : #include "scriptinterface/Request.h"
      34             : #include "simulation2/system/Component.h"
      35             : 
      36             : #include <algorithm>
      37             : #include <boost/algorithm/string/classification.hpp>
      38             : #include <boost/algorithm/string/constants.hpp>
      39             : #include <boost/algorithm/string/join.hpp>
      40             : #include <boost/algorithm/string/split.hpp>
      41             : #include <cstdlib>
      42             : #include <js/CharacterEncoding.h>
      43             : #include <js/PropertyAndElement.h>
      44             : #include <js/RootingAPI.h>
      45             : #include <js/String.h>
      46             : #include <js/Value.h>
      47             : #include <jsapi.h>
      48             : #include <sstream>
      49             : #include <string_view>
      50             : #include <utility>
      51             : #include <vector>
      52             : 
      53             : static CParamNode g_NullNode(false);
      54             : 
      55      369432 : CParamNode::CParamNode(bool isOk) :
      56      369432 :     m_IsOk(isOk)
      57             : {
      58        7630 : }
      59             : 
      60        8498 : void CParamNode::LoadXML(CParamNode& ret, const XMBData& xmb, const wchar_t* sourceIdentifier /*= NULL*/)
      61             : {
      62        8498 :     ret.ApplyLayer(xmb, xmb.GetRoot(), sourceIdentifier);
      63        8476 : }
      64             : 
      65          22 : void CParamNode::LoadXML(CParamNode& ret, const VfsPath& path, const std::string& validatorName)
      66             : {
      67          22 :     CXeromyces xero;
      68          22 :     PSRETURN ok = xero.Load(g_VFS, path, validatorName);
      69          22 :     if (ok != PSRETURN_OK)
      70           0 :         return; // (Xeromyces already logged an error)
      71             : 
      72          44 :     LoadXML(ret, xero, path.string().c_str());
      73          22 : }
      74             : 
      75        5768 : PSRETURN CParamNode::LoadXMLString(CParamNode& ret, const char* xml, const wchar_t* sourceIdentifier /*=NULL*/)
      76             : {
      77        5768 :     CXeromyces xero;
      78        5768 :     PSRETURN ok = xero.LoadString(xml);
      79        5768 :     if (ok != PSRETURN_OK)
      80             :         return ok;
      81             : 
      82        5768 :     ret.ApplyLayer(xero, xero.GetRoot(), sourceIdentifier);
      83             : 
      84        5768 :     return PSRETURN_OK;
      85        5768 : }
      86             : 
      87      442246 : void CParamNode::ApplyLayer(const XMBData& xmb, const XMBElement& element, const wchar_t* sourceIdentifier /*= NULL*/)
      88             : {
      89      884492 :     ResetScriptVal();
      90             : 
      91      442246 :     std::string name = xmb.GetElementString(element.GetNodeName());
      92      442246 :     CStr value = element.GetText();
      93             : 
      94      442246 :     bool hasSetValue = false;
      95             : 
      96             :     // Look for special attributes
      97      442246 :     int at_disable = xmb.GetAttributeID("disable");
      98      442246 :     int at_replace = xmb.GetAttributeID("replace");
      99      442246 :     int at_filtered = xmb.GetAttributeID("filtered");
     100      442246 :     int at_merge = xmb.GetAttributeID("merge");
     101      442246 :     int at_op = xmb.GetAttributeID("op");
     102      442246 :     int at_datatype = xmb.GetAttributeID("datatype");
     103      442246 :     enum op {
     104             :         INVALID,
     105             :         ADD,
     106             :         MUL,
     107             :         MUL_ROUND
     108      442246 :     } op = INVALID;
     109      442246 :     bool replacing = false;
     110      442246 :     bool filtering = false;
     111      442246 :     bool merging = false;
     112      969781 :     for (XMBAttribute attr : element.GetAttributes())
     113             :     {
     114       43448 :         if (attr.Name == at_disable)
     115             :         {
     116        1461 :             m_Childs.erase(name);
     117        1461 :             return;
     118             :         }
     119       41987 :         else if (attr.Name == at_replace)
     120             :         {
     121         631 :             m_Childs.erase(name);
     122         631 :             replacing = true;
     123             :         }
     124       41356 :         else if (attr.Name == at_filtered)
     125             :         {
     126             :             filtering = true;
     127             :         }
     128       41345 :         else if (attr.Name == at_merge)
     129             :         {
     130         332 :             if (m_Childs.find(name) == m_Childs.end())
     131             :                 return;
     132             :             merging = true;
     133             :         }
     134       41013 :         else if (attr.Name == at_op)
     135             :         {
     136        2928 :             if (attr.Value == "add")
     137             :                 op = ADD;
     138        2222 :             else if (attr.Value == "mul")
     139             :                 op = MUL;
     140         165 :             else if (attr.Value == "mul_round")
     141             :                 op = MUL_ROUND;
     142             :             else
     143           0 :                 LOGWARNING("Invalid op '{}'", attr.Value);
     144             :         }
     145       43448 :     }
     146      949502 :     for (XMBAttribute attr : element.GetAttributes())
     147             :     {
     148       41839 :         if (attr.Name == at_datatype && attr.Value == "tokens")
     149             :         {
     150       15454 :             CParamNode& node = m_Childs[name];
     151             : 
     152             :             // Split into tokens
     153       15454 :             std::vector<std::string> oldTokens;
     154       15454 :             std::vector<std::string> newTokens;
     155       15454 :             if (!replacing && !node.m_Value.empty()) // ignore the old tokens if replace="" was given
     156       10664 :                 boost::algorithm::split(oldTokens, node.m_Value, boost::algorithm::is_space(), boost::algorithm::token_compress_on);
     157       15454 :             if (!value.empty())
     158       30808 :                 boost::algorithm::split(newTokens, value, boost::algorithm::is_space(), boost::algorithm::token_compress_on);
     159             : 
     160             :             // Merge the two lists
     161       15454 :             std::vector<std::string> tokens = oldTokens;
     162       57288 :             for (const std::string& newToken : newTokens)
     163             :             {
     164       41834 :                 if (newToken[0] == '-')
     165             :                 {
     166         600 :                     std::vector<std::string>::iterator tokenIt =
     167         600 :                         std::find(tokens.begin(), tokens.end(),
     168         600 :                             std::string_view{newToken}.substr(1));
     169         600 :                     if (tokenIt != tokens.end())
     170         598 :                         tokens.erase(tokenIt);
     171             :                     else
     172             :                     {
     173           2 :                         const std::string identifier{
     174           2 :                             sourceIdentifier ? (" in '" +
     175           2 :                                 utf8_from_wstring(sourceIdentifier) + "'") : ""};
     176           6 :                         LOGWARNING("[ParamNode] Could not remove token "
     177             :                             "'{}' from node '{}'{}; not present in "
     178             :                             "list nor inherited (possible typo?)",
     179             :                             std::string_view{newToken}.substr(1), name,
     180             :                             identifier);
     181           2 :                     }
     182             :                 }
     183             :                 else
     184             :                 {
     185       41234 :                     if (std::find(oldTokens.begin(), oldTokens.end(), newToken) == oldTokens.end())
     186       40892 :                         tokens.push_back(newToken);
     187             :                 }
     188             :             }
     189             : 
     190       15454 :             node.m_Value = boost::algorithm::join(tokens, " ");
     191       15454 :             hasSetValue = true;
     192       15454 :             break;
     193       15454 :         }
     194       26385 :     }
     195             : 
     196             :     // Add this element as a child node
     197      440639 :     CParamNode& node = m_Childs[name];
     198      440639 :     if (op != INVALID)
     199             :     {
     200             :         // TODO: Support parsing of data types other than fixed; log warnings in other cases
     201        2928 :         fixed oldval = node.ToFixed();
     202        2928 :         fixed mod = fixed::FromString(value);
     203             : 
     204        2928 :         switch (op)
     205             :         {
     206         706 :         case ADD:
     207         706 :             node.m_Value = (oldval + mod).ToString();
     208         706 :             break;
     209        2057 :         case MUL:
     210        2057 :             node.m_Value = oldval.Multiply(mod).ToString();
     211        2057 :             break;
     212         165 :         case MUL_ROUND:
     213         165 :             node.m_Value = fixed::FromInt(oldval.Multiply(mod).ToInt_RoundToNearest()).ToString();
     214         165 :             break;
     215             :         default:
     216             :             break;
     217             :         }
     218        2928 :         hasSetValue = true;
     219             :     }
     220             : 
     221      440639 :     if (!hasSetValue && !merging)
     222      422071 :         node.m_Value = value;
     223             : 
     224             :     // We also need to reset node's script val, even if it has no children
     225             :     // or if the attributes change.
     226      881278 :     node.ResetScriptVal();
     227             : 
     228             :     // For the filtered case
     229      881278 :     ChildrenMap childs;
     230             : 
     231             :     // Recurse through the element's children
     232     1737238 :     for (XMBElement child : element.GetChildNodes())
     233             :     {
     234      427980 :         node.ApplyLayer(xmb, child, sourceIdentifier);
     235      427980 :         if (filtering)
     236             :         {
     237         107 :             std::string childname = xmb.GetElementString(child.GetNodeName());
     238         107 :             if (node.m_Childs.find(childname) != node.m_Childs.end())
     239          86 :                 childs[childname] = std::move(node.m_Childs[childname]);
     240         107 :         }
     241             :     }
     242             : 
     243      440639 :     if (filtering)
     244          11 :         node.m_Childs.swap(childs);
     245             : 
     246             :     // Add the element's attributes, prefixing names with "@"
     247     1405599 :     for (XMBAttribute attr : element.GetAttributes())
     248             :     {
     249             :         // Skip special attributes
     250       41841 :         if (attr.Name == at_replace || attr.Name == at_op || attr.Name == at_merge || attr.Name == at_filtered)
     251        3756 :             continue;
     252             :         // Add any others
     253       38085 :         const char* attrName(xmb.GetAttributeString(attr.Name));
     254      114255 :         node.m_Childs[CStr("@") + attrName].m_Value = attr.Value;
     255       41841 :     }
     256      481763 : }
     257             : 
     258        7696 : const CParamNode& CParamNode::GetOnlyChild() const
     259             : {
     260        7696 :     if (m_Childs.empty())
     261             :         return g_NullNode;
     262             : 
     263        7696 :     ENSURE(m_Childs.size() == 1);
     264        7696 :     return m_Childs.begin()->second;
     265             : }
     266             : 
     267       12612 : const CParamNode& CParamNode::GetChild(const char* name) const
     268             : {
     269       12612 :     ChildrenMap::const_iterator it = m_Childs.find(name);
     270       12612 :     if (it == m_Childs.end())
     271             :         return g_NullNode;
     272        9195 :     return it->second;
     273             : }
     274             : 
     275       19583 : bool CParamNode::IsOk() const
     276             : {
     277       19583 :     return m_IsOk;
     278             : }
     279             : 
     280         195 : const std::wstring CParamNode::ToWString() const
     281             : {
     282         195 :     return wstring_from_utf8(m_Value);
     283             : }
     284             : 
     285         811 : const std::string& CParamNode::ToString() const
     286             : {
     287         811 :     return m_Value;
     288             : }
     289             : 
     290           0 : const CStrIntern CParamNode::ToUTF8Intern() const
     291             : {
     292           0 :     return CStrIntern(m_Value);
     293             : }
     294             : 
     295          69 : int CParamNode::ToInt() const
     296             : {
     297          69 :     return std::strtol(m_Value.c_str(), nullptr, 10);
     298             : }
     299             : 
     300        6062 : fixed CParamNode::ToFixed() const
     301             : {
     302       12124 :     return fixed::FromString(m_Value);
     303             : }
     304             : 
     305           0 : float CParamNode::ToFloat() const
     306             : {
     307           0 :     return std::strtof(m_Value.c_str(), nullptr);
     308             : }
     309             : 
     310        2915 : bool CParamNode::ToBool() const
     311             : {
     312        2915 :     if (m_Value == "true")
     313             :         return true;
     314             :     else
     315        2142 :         return false;
     316             : }
     317             : 
     318         229 : const CParamNode::ChildrenMap& CParamNode::GetChildren() const
     319             : {
     320         229 :     return m_Childs;
     321             : }
     322             : 
     323       25161 : std::string CParamNode::EscapeXMLString(const std::string& str)
     324             : {
     325       25161 :     std::string ret;
     326       25161 :     ret.reserve(str.size());
     327             :     // TODO: would be nice to check actual v1.0 XML codepoints,
     328             :     // but our UTF8 validation routines are lacking.
     329      183935 :     for (size_t i = 0; i < str.size(); ++i)
     330             :     {
     331      158774 :         char c = str[i];
     332      158774 :         switch (c)
     333             :         {
     334           4 :         case '<': ret += "&lt;"; break;
     335           2 :         case '>': ret += "&gt;"; break;
     336           1 :         case '&': ret += "&amp;"; break;
     337           1 :         case '"': ret += "&quot;"; break;
     338           1 :         case '\t': ret += "&#9;"; break;
     339           1 :         case '\n': ret += "&#10;"; break;
     340           1 :         case '\r': ret += "&#13;"; break;
     341      158763 :         default:
     342      317537 :             ret += c;
     343             :         }
     344             :     }
     345       25161 :     return ret;
     346           0 : }
     347             : 
     348        7512 : std::string CParamNode::ToXMLString() const
     349             : {
     350        7512 :     std::stringstream strm;
     351        7512 :     ToXMLString(strm);
     352       15024 :     return strm.str();
     353        7512 : }
     354             : 
     355      438035 : void CParamNode::ToXMLString(std::ostream& strm) const
     356             : {
     357      438035 :     strm << m_Value;
     358             : 
     359      438035 :     ChildrenMap::const_iterator it = m_Childs.begin();
     360      893716 :     for (; it != m_Childs.end(); ++it)
     361             :     {
     362             :         // Skip attributes here (they were handled when the caller output the tag)
     363      455681 :         if (it->first.length() && it->first[0] == '@')
     364       25158 :             continue;
     365             : 
     366      430523 :         strm << "<" << it->first;
     367             : 
     368             :         // Output the child's attributes first
     369      430523 :         ChildrenMap::const_iterator cit = it->second.m_Childs.begin();
     370      878685 :         for (; cit != it->second.m_Childs.end(); ++cit)
     371             :         {
     372      448162 :             if (cit->first.length() && cit->first[0] == '@')
     373             :             {
     374       50314 :                 std::string attrname (cit->first.begin()+1, cit->first.end());
     375       75471 :                 strm << " " << attrname << "=\"" << EscapeXMLString(cit->second.m_Value) << "\"";
     376       25157 :             }
     377             :         }
     378             : 
     379      430523 :         strm << ">";
     380             : 
     381      430523 :         it->second.ToXMLString(strm);
     382             : 
     383      430523 :         strm << "</" << it->first << ">";
     384             :     }
     385      438035 : }
     386             : 
     387        4000 : void CParamNode::ToJSVal(const Script::Request& rq, bool cacheValue, JS::MutableHandleValue ret) const
     388             : {
     389        4000 :     if (cacheValue && m_ScriptVal != NULL)
     390             :     {
     391        3278 :         ret.set(*m_ScriptVal);
     392        3278 :         return;
     393             :     }
     394             : 
     395         722 :     ConstructJSVal(rq, ret);
     396             : 
     397         722 :     if (cacheValue)
     398             :     {
     399         722 :         if (ret.isObject())
     400         546 :             Script::DeepFreezeObject(rq, ret);
     401             : 
     402         722 :         m_ScriptVal.reset(new JS::PersistentRootedValue(rq.cx, ret));
     403             :     }
     404             : }
     405             : 
     406        5661 : void CParamNode::ConstructJSVal(const Script::Request& rq, JS::MutableHandleValue ret) const
     407             : {
     408        5661 :     if (m_Childs.empty())
     409             :     {
     410             :         // Empty node - map to undefined
     411        4262 :         if (m_Value.empty())
     412             :         {
     413         239 :             ret.setUndefined();
     414         239 :             return;
     415             :         }
     416             : 
     417             :         // Just a string
     418        4023 :         JS::RootedString str(rq.cx, JS_NewStringCopyUTF8Z(rq.cx, JS::ConstUTF8CharsZ(m_Value.data(), m_Value.size())));
     419        4023 :         if (str)
     420             :         {
     421        4023 :             ret.setString(str);
     422        4023 :             return;
     423             :         }
     424             :         // TODO: report error
     425           0 :         ret.setUndefined();
     426           0 :         return;
     427        4262 :     }
     428             : 
     429             :     // Got child nodes - convert this node into a hash-table-style object:
     430             : 
     431        1399 :     JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx));
     432        1399 :     if (!obj)
     433             :     {
     434           0 :         ret.setUndefined();
     435           0 :         return; // TODO: report error
     436             :     }
     437             : 
     438        1399 :     JS::RootedValue childVal(rq.cx);
     439        6338 :     for (std::map<std::string, CParamNode>::const_iterator it = m_Childs.begin(); it != m_Childs.end(); ++it)
     440             :     {
     441        4939 :         it->second.ConstructJSVal(rq, &childVal);
     442        4939 :         if (!JS_SetProperty(rq.cx, obj, it->first.c_str(), childVal))
     443             :         {
     444           0 :             ret.setUndefined();
     445           0 :             return; // TODO: report error
     446             :         }
     447             :     }
     448             : 
     449             :     // If the node has a string too, add that as an extra property
     450        1399 :     if (!m_Value.empty())
     451             :     {
     452         286 :         JS::RootedString str(rq.cx, JS_NewStringCopyUTF8Z(rq.cx, JS::ConstUTF8CharsZ(m_Value.data(), m_Value.size())));
     453         286 :         if (!str)
     454             :         {
     455           0 :             ret.setUndefined();
     456           0 :             return; // TODO: report error
     457             :         }
     458             : 
     459         286 :         JS::RootedValue subChildVal(rq.cx, JS::StringValue(str));
     460         286 :         if (!JS_SetProperty(rq.cx, obj, "_string", subChildVal))
     461             :         {
     462           0 :             ret.setUndefined();
     463           0 :             return; // TODO: report error
     464             :         }
     465         286 :     }
     466             : 
     467        1399 :     ret.setObject(*obj);
     468        5661 : }
     469             : 
     470      882885 : void CParamNode::ResetScriptVal()
     471             : {
     472      882885 :     m_ScriptVal = NULL;
     473           0 : }

Generated by: LCOV version 1.16