LCOV - code coverage report
Current view: top level - source/graphics - FontManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 92 119 77.3 %
Date: 2026-11-26 14:25:31 Functions: 8 9 88.9 %

          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 "FontManager.h"
      21             : 
      22             : #include "graphics/Font.h"
      23             : #include "i18n/L10n.h"
      24             : #include "lib/file/vfs/vfs_path.h"
      25             : #include "lib/posix/posix.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/containers/StaticVector.h"
      28             : #include "ps/CStr.h"
      29             : #include "ps/CStrInternStatic.h"
      30             : #include "ps/ConfigDB.h"
      31             : #include "ps/Filesystem.h"
      32             : #include "ps/Profiler2.h"
      33             : #include "ps/strings/StringBuilder.h"
      34             : #include "renderer/backend/IDeviceCommandContext.h"
      35             : 
      36             : #include <algorithm>
      37             : #include <cmath>
      38             : #include <fmt/format.h>
      39             : #include <freetype/fttypes.h>
      40             : #include <locale>
      41             : #include <map>
      42             : #include <regex>
      43             : #include <stdexcept>
      44             : #include <string>
      45             : #include <string_view>
      46             : #include <unicode/locid.h>
      47             : #include <utility>
      48             : #include <vector>
      49             : 
      50             : namespace
      51             : {
      52             : 
      53          10 : struct FontSpec
      54             : {
      55             :     std::string type;
      56             :     bool bold{false};
      57             :     bool italic{false};
      58             :     bool stroke{false};
      59             :     int size{0};
      60             : };
      61             : 
      62           5 : FontSpec ParseFontSpec(const std::string& spec)
      63             : {
      64             :     // Regex breakdown:
      65             :     //   ^([^\\-]+)           → capture fontType (one or more non-'-')
      66             :     //   (?:-(bold|italic))?  → optional "-bold" or "-italic"
      67             :     //   (?:-(stroke))?       → optional "-stroke"
      68             :     //   -([0-9]+)$           → "-" then fontSize digits at end
      69             :     // examples:
      70             :     // "Roboto-italic-stroke-24",
      71             :     // "OpenSans-bold-32",
      72             :     // "Arial-stroke-16",
      73             :     // "Lato-14"
      74           5 :     static const std::regex pattern{R"(^([^\-]+)(?:-(bold|italic))?(?:-(stroke))?-([0-9]+)$)",
      75           5 :         std::regex::icase};
      76             : 
      77           5 :     std::smatch m;
      78           5 :     if (!std::regex_match(spec, m, pattern))
      79             :     {
      80           0 :         LOGERROR("Invalid font specification: {}", spec);
      81           0 :         return {};
      82             :     }
      83             : 
      84           5 :     FontSpec fs;
      85          10 :     fs.type = m[1].str();
      86             : 
      87          10 :     if (m[2].matched)
      88             :     {
      89           2 :         std::string style = m[2].str();
      90           1 :         if (strcasecmp(style.c_str(), "bold") == 0)
      91           1 :             fs.bold = true;
      92           0 :         else if (strcasecmp(style.c_str(), "italic") == 0)
      93           0 :             fs.italic = true;
      94           1 :     }
      95             : 
      96          10 :     if (m[3].matched)
      97           0 :         fs.stroke = true;
      98             : 
      99          15 :     fs.size = std::stoi(m[4].str());
     100             : 
     101           5 :     return fs;
     102          10 : }
     103             : } // namespace
     104             : 
     105          10 : CFontManager::CFontManager(Renderer::Backend::IDevice* device)
     106          20 :     : m_GUIScaleHook{std::make_unique<CConfigDBHook>(g_ConfigDB.RegisterHookAndCall(
     107          20 :         "gui.scale", [this]()
     108             :         {
     109          10 :             m_GUIScale = g_ConfigDB.Get("gui.scale", 1.0f);
     110          10 :         }))},
     111          10 :     m_Device(device)
     112             : {
     113          10 :     FT_Library lib;
     114          10 :     FT_Error error{FT_Init_FreeType(&lib)};
     115          10 :     if (error)
     116           0 :         throw std::runtime_error{"Failed to initialize FreeType " + std::to_string(error)};
     117          10 :     m_FreeType.reset(lib);
     118             : 
     119          10 :     m_GammaCorrectionLUT = std::make_unique<std::array<float, 256>>();
     120             : 
     121          10 :     std::generate(m_GammaCorrectionLUT->begin(), m_GammaCorrectionLUT->end(), [i = 0]() mutable {
     122        2560 :         return std::pow((i++) / 255.0f, 1.0f / GAMMA_CORRECTION);
     123             :     });
     124          10 : }
     125             : 
     126          30 : CFontManager::~CFontManager() = default;
     127             : 
     128        2642 : CFont* CFontManager::LoadFont(CStrIntern fontName, CStrIntern locale)
     129             : {
     130        7926 :     const std::string localeToUse{[&]
     131             :         {
     132        2642 :             if (!locale.empty())
     133           0 :                 return locale.string();
     134             : 
     135        2642 :             if (g_L10n.GetCurrentLocale() == icu::Locale::getUS())
     136           0 :                 return std::string{};
     137             : 
     138             :             // Use the current locale, but not US English.
     139        2642 :             return g_L10n.GetCurrentLocaleString();
     140             :         } ()
     141        2642 :     };
     142             :     // fmt::format_to_n is expensive for frequent LoadFont calls, parsing the
     143             :     // format string takes a noticeable amount of time.
     144        2642 :     char buffer[128];
     145        2642 :     PS::StringBuilder fontNameBuilder{{std::begin(buffer), std::end(buffer)}};
     146        2642 :     fontNameBuilder.Append(localeToUse);
     147        2642 :     fontNameBuilder.Append(fontName.string());
     148        2642 :     fontNameBuilder.Append('-');
     149        2642 :     fontNameBuilder.Append(m_GUIScale);
     150        2642 :     CStrIntern localeFontName{fontNameBuilder.Str()};
     151             : 
     152        2642 :     FontsMap::iterator it{m_Fonts.find(localeFontName)};
     153        2642 :     if (it != m_Fonts.end())
     154        2637 :         return &it->second;
     155             : 
     156             :     // TODO: use hooks or something to hotrealoding default font.
     157          10 :     const std::string defaultFont{g_ConfigDB.Get("fonts.default", std::string{})};
     158             : 
     159           5 :     if (defaultFont.empty())
     160             :     {
     161           0 :         LOGERROR("Default font not set in config");
     162           0 :         return nullptr;
     163             :     }
     164             : 
     165             :     // FontName contain the format fontType(-fontBold|fontItalic)(-fontStroke)-fontSize.
     166             :     // We are going to split it to get the fontType and fontSize.
     167           5 :     FontSpec fontSpec{ParseFontSpec(fontName.string())};
     168             : 
     169           5 :     if (fontSpec.type.empty())
     170             :     {
     171           0 :         LOGERROR("Failed to parse font specification: {}, using default font", fontName.string());
     172           0 :         fontSpec = ParseFontSpec(str_sans_10.string());
     173             :     }
     174             : 
     175             :     // Check for font configuration or fallback.
     176           0 :     const std::map<CStr, CConfigValueSet> fontToSearch{[&]
     177             :         {
     178             :             // full locale + short locale + global each with up to 3 styles.
     179           5 :             PS::StaticVector<std::string, 9> candidateFonts;
     180             : 
     181          20 :             auto addCandidate{ [&](const std::string_view localeName)
     182             :             {
     183          15 :                 std::string localePart{localeName};
     184          15 :                 if (!localePart.empty())
     185          10 :                     localePart.push_back('.');
     186          15 :                 if (fontSpec.bold)
     187           9 :                     candidateFonts.push_back(fmt::format("fonts.{}{}.bold", localePart, fontSpec.type));
     188          15 :                 if (fontSpec.italic)
     189           0 :                     candidateFonts.push_back(fmt::format("fonts.{}{}.italic", localePart, fontSpec.type));
     190          45 :                 candidateFonts.push_back(fmt::format("fonts.{}{}.regular", localePart, fontSpec.type));
     191          15 :             }};
     192             : 
     193             :             // TODO: explicit Locale like RTL or Arabic fonts.
     194             :             // 1. Locale-specific fonts first.
     195           5 :             if (!localeToUse.empty())
     196             :             {
     197             :                 // Full locale first, e.g. zh_TW.
     198           5 :                 addCandidate(localeToUse);
     199             : 
     200             :                 // Then short locale, e.g. zh.
     201           5 :                 if (const size_t pos{localeToUse.find('_')}; pos != std::string::npos)
     202             :                 {
     203           5 :                     const std::string shortLocale{localeToUse.substr(0, pos)};
     204           5 :                     addCandidate(shortLocale);
     205           5 :                 }
     206             :             }
     207             : 
     208             :             // 2. Then global fonts
     209           5 :             const std::string globalLocale{};
     210           5 :             addCandidate(globalLocale);
     211             : 
     212          17 :             for (const std::string& key : candidateFonts)
     213             :             {
     214          34 :                 std::map<CStr, CConfigValueSet> value{g_ConfigDB.GetValuesWithPrefix(CFG_COMMAND, key)};
     215          34 :                 std::map<CStr, CConfigValueSet>::iterator item{value.find(key)};
     216             : 
     217          17 :                 if (item != value.end() && !item->second.empty())
     218          10 :                     return value;
     219          17 :             }
     220             : 
     221             :             // Fallback to default.
     222           0 :             return g_ConfigDB.GetValuesWithPrefix(CFG_COMMAND, defaultFont);
     223          10 :         }()
     224           5 :     };
     225             : 
     226           5 :     CFont font{this->m_FreeType.get(), *m_GammaCorrectionLUT};
     227             : 
     228          10 :     if (!font.SetFontParams(m_Device, localeFontName.string(), fontSpec.size, fontSpec.stroke ? 1.0f : 0.0f, m_GUIScale))
     229             :     {
     230           0 :         LOGERROR("Failed to set font params for {}", localeFontName.string());
     231           0 :         return nullptr;
     232             :     }
     233             : 
     234           5 :     const VfsPath path(L"fonts/");
     235          10 :     for (const std::pair<const CStr, CConfigValueSet>& configPair : fontToSearch)
     236             :     {
     237          10 :         for (const CStr& fontPath : configPair.second)
     238             :         {
     239           5 :             const VfsPath fntPath{path / fontPath};
     240           5 :             if (!VfsFileExists(fntPath))
     241             :             {
     242           0 :                 LOGERROR("Font file {} not found", fontPath);
     243           0 :                 return nullptr;
     244             :             }
     245             : 
     246           5 :             if (!font.AddFontFromPath(fntPath))
     247             :             {
     248           0 :                 LOGERROR("Failed to load font {}", fntPath.string8());
     249           0 :                 return nullptr;
     250             :             }
     251           5 :         }
     252             :     }
     253             : 
     254             :     // Preload the common characters for visual quality.
     255             :     // Common characters are: Latin, numbers, punctuation.
     256         475 :     std::string_view glypshSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,;:!?\"'()[]{}<>-+=_@#$%^&*`~\\|/";
     257         475 :     for (const char c : glypshSet)
     258         470 :         font.GetGlyph(c);
     259             : 
     260           5 :     return &m_Fonts.insert_or_assign(localeFontName, std::move(font)).first->second;
     261        2652 : }
     262             : 
     263           0 : void CFontManager::UploadAtlasTexturesToGPU(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     264             : {
     265           0 :     PROFILE2("Loading font textures");
     266           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Loading font textures");
     267             : 
     268           0 :     for (auto& [fontName, font] : m_Fonts)
     269           0 :         font.UploadAtlasTextureToGPU(deviceCommandContext);
     270           0 : }

Generated by: LCOV version 1.16