LCOV - code coverage report
Current view: top level - source/ps - Mod.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 76 181 42.0 %
Date: 2026-12-03 01:19:39 Functions: 3 13 23.1 %

          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 "Mod.h"
      21             : 
      22             : #include "lib/file/file_system.h"
      23             : #include "lib/file/vfs/vfs.h"
      24             : #include "lib/path.h"
      25             : #include "lib/sysdep/os.h"
      26             : #include "lib/utf8.h"
      27             : #include "ps/CLogger.h"
      28             : #include "ps/Errors.h"
      29             : #include "ps/Filesystem.h"
      30             : #include "ps/GameSetup/CmdLineArgs.h"
      31             : #include "ps/GameSetup/Paths.h"
      32             : #include "ps/Profiler2.h"
      33             : #include "scriptinterface/JSON.h"
      34             : #include "scriptinterface/Object.h"
      35             : #include "scriptinterface/Conversions.h"
      36             : #include "scriptinterface/Request.h"
      37             : 
      38             : #include <algorithm>
      39             : #include <boost/algorithm/string/classification.hpp>
      40             : #include <boost/algorithm/string/constants.hpp>
      41             : #include <boost/algorithm/string/split.hpp>
      42             : #include <cstddef>
      43             : #include <fstream>
      44             : #include <js/RootingAPI.h>
      45             : #include <js/TypeDecls.h>
      46             : #include <js/Value.h>
      47             : #include <sstream>
      48             : #include <string>
      49             : #include <unordered_map>
      50             : #include <utility>
      51             : 
      52             : #if OS_WIN
      53             : #include <filesystem>
      54             : #else
      55             : #include "lib/os_path.h"
      56             : #endif
      57             : 
      58             : namespace Script { class Interface; }
      59             : 
      60             : namespace
      61             : {
      62             : /**
      63             :  * Global instance of Mod, always exists.
      64             :  */
      65             : Mod g_ModInstance;
      66             : 
      67           0 : bool LoadModJSON(const PIVFS& vfs, OsPath modsPath, OsPath mod, std::string& text)
      68             : {
      69             : #if OS_WIN
      70             :     const std::filesystem::path modJsonPath = (modsPath / mod / L"mod.json").fileSystemPath();
      71             : #else
      72           0 :     const std::string modJsonPath = OsString(modsPath / mod / L"mod.json");
      73             : #endif
      74             :     // Attempt to open mod.json first.
      75           0 :     std::ifstream modjson(modJsonPath);
      76           0 :     if (!modjson)
      77             :     {
      78           0 :         modjson.close();
      79             : 
      80             :         // Fallback: open the archive and read mod.json there.
      81             :         // This can take in the hundreds of milliseconds with large mods.
      82           0 :         vfs->Clear();
      83           0 :         if (vfs->Mount(L"", modsPath / mod / "", VFS_MOUNT_MUST_EXIST, VFS_MIN_PRIORITY) < 0)
      84             :             return false;
      85             : 
      86           0 :         CVFSFile modinfo;
      87           0 :         if (modinfo.Load(vfs, L"mod.json", false) != PSRETURN_OK)
      88             :             return false;
      89             : 
      90           0 :         text = modinfo.GetAsString();
      91             : 
      92             :         // Attempt to write the mod.json file so we'll take the fast path next time.
      93           0 :         std::ofstream out_mod_json(modJsonPath);
      94           0 :         if (out_mod_json)
      95             :         {
      96           0 :             out_mod_json << text;
      97           0 :             out_mod_json.close();
      98             :         }
      99             :         else
     100             :         {
     101             :             // Print a warning - we'll keep trying, which could have adverse effects.
     102           0 :             LOGWARNING("Could not write external mod.json for zipped mod '{}'. The mod should be "
     103             :                 "reinstalled.", mod.string8());
     104             :         }
     105           0 :         return true;
     106           0 :     }
     107             :     else
     108             :     {
     109           0 :         std::stringstream buffer;
     110           0 :         buffer << modjson.rdbuf();
     111           0 :         text = buffer.str();
     112           0 :         return true;
     113           0 :     }
     114           0 : }
     115             : 
     116           0 : bool ParseModJSON(const Script::Request& rq, const PIVFS& vfs, OsPath modsPath, OsPath mod, Mod::ModData& data)
     117             : {
     118           0 :     std::string text;
     119           0 :     if (!LoadModJSON(vfs, modsPath, mod, text))
     120             :         return false;
     121             : 
     122           0 :     JS::RootedValue json(rq.cx);
     123           0 :     if (!Script::ParseJSON(rq, text, &json))
     124             :         return false;
     125             : 
     126           0 :     Script::FromJSVal(rq, json, data);
     127             : 
     128             :     // Complete - FromJSVal won't convert everything.
     129           0 :     data.m_Pathname = utf8_from_wstring(mod.string());
     130           0 :     data.m_Text = text;
     131           0 :     if (!Script::GetProperty(rq, json, "dependencies", data.m_Dependencies))
     132             :         return false;
     133             :     return true;
     134           0 : }
     135             : 
     136             : } // anonymous namespace
     137             : 
     138           0 : Mod& Mod::Instance()
     139             : {
     140           0 :     return g_ModInstance;
     141             : }
     142             : 
     143           0 : const std::vector<CStr>& Mod::GetEnabledMods() const
     144             : {
     145           0 :     return m_EnabledMods;
     146             : }
     147             : 
     148           0 : const std::vector<CStr>& Mod::GetIncompatibleMods() const
     149             : {
     150           0 :     return m_IncompatibleMods;
     151             : }
     152             : 
     153           0 : const std::vector<Mod::ModData>& Mod::GetAvailableMods() const
     154             : {
     155           0 :     return m_AvailableMods;
     156             : }
     157             : 
     158           0 : bool Mod::EnableMods(const std::vector<CStr>& mods, const bool addPublic)
     159             : {
     160           0 :     m_IncompatibleMods.clear();
     161           0 :     m_EnabledMods.clear();
     162             : 
     163           0 :     std::unordered_map<CStr, int> counts;
     164           0 :     for (const CStr& mod : mods)
     165             :     {
     166             :         // Ignore duplicates.
     167           0 :         if (counts.try_emplace(mod, 0).first->second++ > 0)
     168           0 :             continue;
     169           0 :         m_EnabledMods.emplace_back(mod);
     170             :     }
     171             : 
     172           0 :     if (addPublic && counts["public"] == 0)
     173           0 :         m_EnabledMods.insert(m_EnabledMods.begin(), "public");
     174             : 
     175           0 :     if (counts["mod"] == 0)
     176           0 :         m_EnabledMods.insert(m_EnabledMods.begin(), "mod");
     177             : 
     178           0 :     m_IncompatibleMods = CheckForIncompatibleMods(m_EnabledMods);
     179             : 
     180           0 :     for (const CStr& mod : m_IncompatibleMods)
     181           0 :         m_EnabledMods.erase(std::find(m_EnabledMods.begin(), m_EnabledMods.end(), mod));
     182             : 
     183           0 :     return m_IncompatibleMods.empty();
     184           0 : }
     185             : 
     186           0 : const Mod::ModData* Mod::GetModData(const CStr& mod) const
     187             : {
     188           0 :     std::vector<ModData>::const_iterator it = std::find_if(m_AvailableMods.begin(), m_AvailableMods.end(),
     189           0 :         [&mod](const ModData& modData) { return modData.m_Pathname == mod; });
     190           0 :     if (it == m_AvailableMods.end())
     191           0 :         return nullptr;
     192             :     return std::addressof(*it);
     193             : }
     194             : 
     195           0 : const std::vector<const Mod::ModData*> Mod::GetEnabledModsData() const
     196             : {
     197           0 :     std::vector<const ModData*> loadedMods;
     198           0 :     for (const CStr& mod : m_EnabledMods)
     199             :     {
     200           0 :         if (mod == "mod" || mod == "user")
     201           0 :             continue;
     202             : 
     203           0 :         const ModData* data = GetModData(mod);
     204             : 
     205             :         // This ought be impossible, but let's handle it anyways since it's not a reason to crash.
     206           0 :         if (!data)
     207             :         {
     208           0 :             LOGERROR("Unavailable mod '{}' was enabled.", mod);
     209           0 :             continue;
     210           0 :         }
     211             : 
     212           0 :         loadedMods.emplace_back(data);
     213             :     }
     214           0 :     return loadedMods;
     215           0 : }
     216             : 
     217           6 : bool Mod::AreModsPlayCompatible(const std::vector<const Mod::ModData*>& modsA, const std::vector<const Mod::ModData*>& modsB)
     218             : {
     219             :     // Mods must be loaded in the same order.
     220           6 :     std::vector<const Mod::ModData*>::const_iterator a = modsA.begin();
     221           6 :     std::vector<const Mod::ModData*>::const_iterator b = modsB.begin();
     222             : 
     223          11 :     while (a != modsA.end() || b != modsB.end())
     224             :     {
     225          14 :         if (a != modsA.end() && (*a)->m_IgnoreInCompatibilityChecks)
     226             :         {
     227           3 :             ++a;
     228           3 :             continue;
     229             :         }
     230          11 :         if (b != modsB.end() && (*b)->m_IgnoreInCompatibilityChecks)
     231             :         {
     232           3 :             ++b;
     233           3 :             continue;
     234             :         }
     235             :         // If at this point one of the two lists still contains items, the sizes are different -> fail.
     236           8 :         if (a == modsA.end() || b == modsB.end())
     237             :             return false;
     238             : 
     239           7 :         if ((*a)->m_Pathname != (*b)->m_Pathname)
     240             :             return false;
     241           7 :         if ((*a)->m_Version != (*b)->m_Version)
     242             :             return false;
     243           5 :         ++a;
     244          22 :         ++b;
     245             :     }
     246             :     return true;
     247             : }
     248             : 
     249           0 : void Mod::UpdateAvailableMods(const Script::Interface& scriptInterface)
     250             : {
     251           0 :     PROFILE2("UpdateAvailableMods");
     252             : 
     253           0 :     m_AvailableMods.clear();
     254           0 :     const Paths paths(g_CmdLineArgs);
     255             : 
     256             :     // loop over all possible paths
     257           0 :     OsPath modPath = paths.RData()/"mods";
     258           0 :     OsPath modUserPath = paths.UserData()/"mods";
     259             : 
     260           0 :     DirectoryNames modDirs;
     261           0 :     DirectoryNames modDirsUser;
     262             : 
     263           0 :     GetDirectoryEntries(modPath, NULL, &modDirs);
     264             :     // Sort modDirs so that we can do a fast lookup below
     265           0 :     std::sort(modDirs.begin(), modDirs.end());
     266             : 
     267           0 :     PIVFS vfs = CreateVfs();
     268             : 
     269           0 :     Script::Request rq(scriptInterface);
     270           0 :     for (DirectoryNames::iterator iter = modDirs.begin(); iter != modDirs.end(); ++iter)
     271             :     {
     272           0 :         ModData data;
     273           0 :         if (!ParseModJSON(rq, vfs, modPath, *iter, data))
     274           0 :             continue;
     275             :         // Valid mod data, add it to our structure
     276           0 :         m_AvailableMods.emplace_back(std::move(data));
     277           0 :     }
     278             : 
     279           0 :     GetDirectoryEntries(modUserPath, NULL, &modDirsUser);
     280             : 
     281           0 :     for (DirectoryNames::iterator iter = modDirsUser.begin(); iter != modDirsUser.end(); ++iter)
     282             :     {
     283             :         // Ignore mods in the user folder if we have already found them in modDirs.
     284           0 :         if (std::binary_search(modDirs.begin(), modDirs.end(), *iter))
     285           0 :             continue;
     286             : 
     287           0 :         ModData data;
     288           0 :         if (!ParseModJSON(rq, vfs, modUserPath, *iter, data))
     289           0 :             continue;
     290             :         // Valid mod data, add it to our structure
     291           0 :         m_AvailableMods.emplace_back(std::move(data));
     292           0 :     }
     293           0 : }
     294             : 
     295           8 : std::vector<CStr> Mod::CheckForIncompatibleMods(const std::vector<CStr>& mods) const
     296             : {
     297           8 :     std::vector<CStr> incompatibleMods;
     298           8 :     std::unordered_map<CStr, std::vector<CStr>> modDependencies;
     299           8 :     std::unordered_map<CStr, CStr> modNameVersions;
     300          22 :     for (const CStr& mod : mods)
     301             :     {
     302          14 :         if (mod == "mod" || mod == "user")
     303           1 :             continue;
     304             : 
     305          13 :         std::vector<ModData>::const_iterator it = std::find_if(m_AvailableMods.begin(), m_AvailableMods.end(),
     306          14 :             [&mod](const ModData& modData) { return modData.m_Pathname == mod; });
     307             : 
     308          13 :         if (it == m_AvailableMods.end())
     309             :         {
     310           1 :             incompatibleMods.push_back(mod);
     311           1 :             continue;
     312             :         }
     313             : 
     314          12 :         modNameVersions.emplace(it->m_Name, it->m_Version);
     315          14 :         modDependencies.emplace(it->m_Pathname, it->m_Dependencies);
     316             :     }
     317             : 
     318          14 :     static const std::vector<CStr> toCheck = { "<=", ">=", "=", "<", ">" };
     319          22 :     for (const CStr& mod : mods)
     320             :     {
     321          14 :         if (mod == "mod" || mod == "user")
     322           9 :             continue;
     323             : 
     324          13 :         const std::unordered_map<CStr, std::vector<CStr>>::iterator res = modDependencies.find(mod);
     325          13 :         if (res == modDependencies.end())
     326           1 :             continue;
     327          12 :         const std::vector<CStr> deps = res->second;
     328          12 :         if (deps.empty())
     329           7 :             continue;
     330             : 
     331          10 :         for (const CStr& dep : deps)
     332             :         {
     333           5 :             if (dep.empty())
     334           0 :                 continue;
     335             :             // 0ad<=0.0.24
     336          13 :             for (const CStr& op : toCheck)
     337             :             {
     338          13 :                 const std::size_t pos{dep.find(op)};
     339          13 :                 if (pos == std::string::npos)
     340           8 :                     continue;
     341             :                 //0ad
     342          10 :                 const CStr modToCheck = dep.substr(0, pos);
     343             :                 //0.0.24
     344          10 :                 const CStr versionToCheck = dep.substr(pos + op.size());
     345           5 :                 const std::unordered_map<CStr, CStr>::iterator it = modNameVersions.find(modToCheck);
     346             :                 // Could not find the mod, or 0.0.25(0ad) , <=, 0.0.24(required version)
     347           5 :                 if (it == modNameVersions.end() || !CompareVersionStrings(it->second, op, versionToCheck))
     348           3 :                     incompatibleMods.push_back(mod);
     349           5 :                 break;
     350           5 :             }
     351             :         }
     352             : 
     353          12 :     }
     354             : 
     355           8 :     return incompatibleMods;
     356          10 : }
     357             : 
     358          29 : bool Mod::CompareVersionStrings(const CStr& version, const CStr& op, const CStr& required) const
     359             : {
     360          29 :     std::vector<CStr> versionSplit;
     361          29 :     std::vector<CStr> requiredSplit;
     362          29 :     static const std::string toIgnore = "-,_";
     363          29 :     boost::split(versionSplit, version, boost::is_any_of(toIgnore), boost::token_compress_on);
     364          29 :     boost::split(requiredSplit, required, boost::is_any_of(toIgnore), boost::token_compress_on);
     365          29 :     boost::split(versionSplit, versionSplit[0], boost::is_any_of("."), boost::token_compress_on);
     366          29 :     boost::split(requiredSplit, requiredSplit[0], boost::is_any_of("."), boost::token_compress_on);
     367             : 
     368          29 :     const bool eq = op.find("=") != std::string::npos;
     369          29 :     const bool lt = op.find("<") != std::string::npos;
     370          29 :     const bool gt = op.find(">") != std::string::npos;
     371             : 
     372          29 :     const size_t min = std::min(versionSplit.size(), requiredSplit.size());
     373             : 
     374          88 :     for (size_t i = 0; i < min; ++i)
     375             :     {
     376          77 :         const int diff = versionSplit[i].ToInt() - requiredSplit[i].ToInt();
     377          77 :         if ((gt && diff > 0) || (lt && diff < 0))
     378             :             return true;
     379             : 
     380          70 :         if ((gt && diff < 0) || (lt && diff > 0) || (eq && diff))
     381             :             return false;
     382             :     }
     383             : 
     384          11 :     const size_t versionSize = versionSplit.size();
     385          11 :     const size_t requiredSize = requiredSplit.size();
     386          11 :     if (versionSize == requiredSize)
     387             :         return eq;
     388           5 :     return versionSize < requiredSize ? lt : gt;
     389          29 : }

Generated by: LCOV version 1.16