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: 69 167 41.3 %
Date: 2022-06-14 00:41:00 Functions: 3 15 20.0 %

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

Generated by: LCOV version 1.13