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: 79 184 42.9 %
Date: 2023-01-19 00:18:29 Functions: 6 17 35.3 %

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

Generated by: LCOV version 1.13