Read the system CJK font once, and hold fonts as ImFont pointers

Each of the four fonts merged the system CJK font from a fresh read of its file, twice, and never freed it.
It is now read once and shared. Startup memory with a document open went from 412 MB to 269 MB.
This commit is contained in:
shweet committed 2026-11-22 17:44:07 -05:00
1 parent 2f1e75da37
commit 20209e655e
12 files changed
+58 -106

No files matched your search

-56
View File
@@ -1,56 +0,0 @@
#include "font.h"
Font::Font() = default;
Font::Font(void* data, size_t length, int size)
{
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
pointer = ImGui::GetIO().Fonts->AddFontFromMemoryTTF(data, length, size, &config);
}
Font::Font(const char* path, int size, int number)
{
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
config.FontNo = number;
pointer = ImGui::GetIO().Fonts->AddFontFromFileTTF(path, size);
}
void Font::append(void* data, size_t length, int size)
{
ImFontConfig config;
config.MergeMode = true;
config.FontDataOwnedByAtlas = false;
ImGui::GetIO().Fonts->AddFontFromMemoryTTF(data, length, size, &config);
}
bool Font::append(const char* path, int size, int number)
{
ImFontConfig config;
config.MergeMode = true;
config.FontDataOwnedByAtlas = false;
config.FontNo = number;
return ImGui::GetIO().Fonts->AddFontFromFileTTF(path, size, &config);
}
Font::~Font()
{
if (get())
ImGui::GetIO().Fonts->RemoveFont(pointer);
}
ImFont* Font::get()
{
return pointer;
}
Font& Font::operator=(Font&& other) noexcept
{
if (this != &other)
{
pointer = other.pointer;
other.pointer = nullptr;
}
return *this;
}
-15
View File
@@ -17,18 +17,3 @@ enum FontStyle
constexpr const Embed* FONTS[FONT_COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF, constexpr const Embed* FONTS[FONT_COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF,
&FONT_BOLD_ITALICS_TTF}; &FONT_BOLD_ITALICS_TTF};
class Font
{
ImFont* pointer = nullptr;
public:
Font();
Font(void*, size_t, int);
Font(const char* path, int size, int number = 0);
void append(void*, size_t, int);
bool append(const char* path, int size, int number = 0);
~Font();
ImFont* get();
Font& operator=(Font&&) noexcept;
};
+41 -18
View File
@@ -2,8 +2,11 @@
#include <ranges> #include <ranges>
#include "file.h"
#include "log.h" #include "log.h"
#include <map>
#ifdef _WIN32 #ifdef _WIN32
static constexpr const char* CHINESE_FALLBACK = "C:\\Windows\\Fonts\\msyh.ttc"; static constexpr const char* CHINESE_FALLBACK = "C:\\Windows\\Fonts\\msyh.ttc";
static constexpr const char* KOREAN_FALLBACK = "C:\\Windows\\Fonts\\malgun.ttf"; static constexpr const char* KOREAN_FALLBACK = "C:\\Windows\\Fonts\\malgun.ttf";
@@ -16,27 +19,47 @@ static constexpr int CHINESE_FALLBACK_NUMBER = 2;
static constexpr int KOREAN_FALLBACK_NUMBER = 1; static constexpr int KOREAN_FALLBACK_NUMBER = 1;
#endif #endif
// A font the atlas reads from memory it doesn't own, number `number` in its file.
struct FontSource
{
const void* data = nullptr;
std::size_t size = 0;
int number = 0;
};
// A system font with the CJK glyphs the embedded subsets lack, read once and kept, as the atlas reads from it.
// The embedded subset when the system one isn't there.
static FontSource fallback_get(const char* path, int number, const Embed& embedded)
{
static std::map<std::string, std::string> files;
auto [it, isNew] = files.try_emplace(path);
if (isNew && !file_text_load(path, &it->second))
logger.error(std::format("Failed to load CJK fallback font: {}", path));
if (it->second.empty())
return {embedded.data, embedded.size, 0};
return {it->second.data(), it->second.size(), number};
}
// A new font, or more glyphs for `target`.
static ImFont* font_add(FontSource source, ImFont* target)
{
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
config.FontNo = source.number;
config.MergeMode = target != nullptr;
config.DstFont = target;
return ImGui::GetIO().Fonts->AddFontFromMemoryTTF((void*)source.data, (int)source.size, FONT_SIZE, &config);
}
Resources::Resources() Resources::Resources()
{ {
auto isKoreanFallback = std::filesystem::exists(KOREAN_FALLBACK); auto korean = fallback_get(KOREAN_FALLBACK, KOREAN_FALLBACK_NUMBER, FONT_KOREAN_TTF);
auto isChineseFallback = std::filesystem::exists(CHINESE_FALLBACK); auto chinese = fallback_get(CHINESE_FALLBACK, CHINESE_FALLBACK_NUMBER, FONT_CHINESE_TTF);
for (int i = 0; i < FONT_COUNT; ++i)
if (!isKoreanFallback)
logger.error(std::format("Failed to load Korean fallback font: {}", KOREAN_FALLBACK));
if (!isChineseFallback)
logger.error(std::format("Failed to load Chinese fallback font: {}", CHINESE_FALLBACK));
for (auto [i, fontInfo] : std::views::enumerate(FONTS))
{ {
fonts[i] = Font((void*)fontInfo->data, fontInfo->size, FONT_SIZE); fonts[i] = font_add({FONTS[i]->data, FONTS[i]->size}, nullptr);
if (isKoreanFallback) font_add(korean, fonts[i]);
fonts[i].append(KOREAN_FALLBACK, FONT_SIZE, KOREAN_FALLBACK_NUMBER); font_add(chinese, fonts[i]);
else
fonts[i].append((void*)FONT_KOREAN_TTF.data, FONT_KOREAN_TTF.size, FONT_SIZE);
if (isChineseFallback)
fonts[i].append(CHINESE_FALLBACK, FONT_SIZE, CHINESE_FALLBACK_NUMBER);
else
fonts[i].append((void*)FONT_CHINESE_TTF.data, FONT_CHINESE_TTF.size, FONT_SIZE);
} }
for (auto [i, iconInfo] : std::views::enumerate(ICONS)) for (auto [i, iconInfo] : std::views::enumerate(ICONS))
+1 -1
View File
@@ -11,7 +11,7 @@
class Resources class Resources
{ {
public: public:
Font fonts[FONT_COUNT]{}; ImFont* fonts[FONT_COUNT] = {};
Image icons[ICON_COUNT]{}; Image icons[ICON_COUNT]{};
ShaderProgram shaders[SHADER_COUNT]{}; ShaderProgram shaders[SHADER_COUNT]{};
AudioData music = {}; AudioData music = {};
+2 -2
View File
@@ -272,7 +272,7 @@ static void friend_canvas_draw(About::FriendState& state, Resources& resources)
// The application name, as large as fits its row. // The application name, as large as fits its row.
static void title_draw(About& about, Resources& resources, const char* title, float width) static void title_draw(About& about, Resources& resources, const char* title, float width)
{ {
auto font = resources.fonts[FONT_BOLD].get(); auto font = resources.fonts[FONT_BOLD];
auto fontSize = (float)FONT_SIZE_LARGE * TITLE_SCALE; auto fontSize = (float)FONT_SIZE_LARGE * TITLE_SCALE;
fontSize *= std::min(1.0f, width / font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title).x); fontSize *= std::min(1.0f, width / font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title).x);
auto textSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title); auto textSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title);
@@ -366,7 +366,7 @@ static void roll_text_draw(ImDrawList* drawList, Resources& resources, const Abo
if (!*credit.string || y + lineHeight < min.y || y > max.y) if (!*credit.string || y + lineHeight < min.y || y > max.y)
continue; continue;
auto font = resources.fonts[credit.font].get(); auto font = resources.fonts[credit.font];
auto x = auto x =
centerX - font->CalcTextSizeA(lineHeight, FLT_MAX, 0.0f, credit.string).x * 0.5f + frame.offsetX * scale; centerX - font->CalcTextSizeA(lineHeight, FLT_MAX, 0.0f, credit.string).x * 0.5f + frame.offsetX * scale;
if (frame.effect == EFFECT_WAVE) if (frame.effect == EFFECT_WAVE)
+1 -1
View File
@@ -891,7 +891,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto textPos = to_imvec2(to_vec2(cursorScreenPos) + to_vec2(ImGui::GetStyle().WindowPadding)); auto textPos = to_imvec2(to_vec2(cursorScreenPos) + to_vec2(ImGui::GetStyle().WindowPadding));
drawList->PushClipRect(clipMin, clipMax); drawList->PushClipRect(clipMin, clipMax);
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE_LARGE);
auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK; auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK;
drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), names.c_str()); drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), names.c_str());
ImGui::PopFont(); ImGui::PopFont();
+1 -1
View File
@@ -720,7 +720,7 @@ void animations_update(Panel& panel, AnimationsPanel& animations)
tooltip_name_draw(resources, animation.name); tooltip_name_draw(resources, animation.name);
if (model.animations.defaultAnimation == animation.name) if (model.animations.defaultAnimation == animation.name)
{ {
ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_ITALICS], FONT_SIZE);
ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); ImGui::TextUnformatted(localize.get(BASIC_DEFAULT));
ImGui::PopFont(); ImGui::PopFont();
} }
+1 -1
View File
@@ -212,7 +212,7 @@ void Documents::update(Taskbar& taskbar, Manager& manager, Settings& settings, R
if (isRequested) if (isRequested)
flags |= ImGuiTabItemFlags_SetSelected; flags |= ImGuiTabItemFlags_SetSelected;
ImGui::PushFont(resources.fonts[font].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[font], FONT_SIZE);
if (ImGui::BeginTabItem(label.c_str(), &document.isOpen, flags)) if (ImGui::BeginTabItem(label.c_str(), &document.isOpen, flags))
{ {
if (manager.selected != i) if (manager.selected != i)
+3 -3
View File
@@ -130,7 +130,7 @@ bool row_draw(Panel& panel, std::set<int>& selection, int& focus, const ListRows
ImGui::PushID(key); ImGui::PushID(key);
ImGui::SetNextItemSelectionUserData(index); ImGui::SetNextItemSelectionUserData(index);
if (font != FONT_REGULAR) if (font != FONT_REGULAR)
ImGui::PushFont(panel.resources.fonts[font].get(), FONT_SIZE); ImGui::PushFont(panel.resources.fonts[font], FONT_SIZE);
if (isInvalid) if (isInvalid)
ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID); ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID);
if (arrowKey == key) if (arrowKey == key)
@@ -244,7 +244,7 @@ static void card_draw(Panel& panel, std::set<int>& selection, int& focus, const
ImGui::SetCursorPos( ImGui::SetCursorPos(
ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2));
if (isFocused) if (isFocused)
ImGui::PushFont(panel.resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::PushFont(panel.resources.fonts[FONT_ITALICS], FONT_SIZE);
ImGui::TextUnformatted(label.c_str()); ImGui::TextUnformatted(label.c_str());
if (isFocused) if (isFocused)
ImGui::PopFont(); ImGui::PopFont();
@@ -476,7 +476,7 @@ void list_panel_draw(Panel& panel, Actions& actions, const Footer& footer, const
void tooltip_name_draw(Resources& resources, const std::string& name) void tooltip_name_draw(Resources& resources, const std::string& name)
{ {
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(name.c_str()); ImGui::TextUnformatted(name.c_str());
ImGui::PopFont(); ImGui::PopFont();
} }
+1 -1
View File
@@ -402,7 +402,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
if (tool == TOOL_PAN && hoveredRegionId != -1 && spritesheet) if (tool == TOOL_PAN && hoveredRegionId != -1 && spritesheet)
if (auto region = region_get(hoveredRegionId); region && ImGui::BeginTooltip()) if (auto region = region_get(hoveredRegionId); region && ImGui::BeginTooltip())
{ {
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(region->name.c_str()); ImGui::TextUnformatted(region->name.c_str());
ImGui::PopFont(); ImGui::PopFont();
auto originLabel = localize.get(region->origin == Origin::TOP_LEFT ? LABEL_REGION_ORIGIN_TOP_LEFT auto originLabel = localize.get(region->origin == Origin::TOP_LEFT ? LABEL_REGION_ORIGIN_TOP_LEFT
+6 -6
View File
@@ -155,7 +155,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
if (isGroupTooltipDelayed && !isVisibleButtonHovered) if (isGroupTooltipDelayed && !isVisibleButtonHovered)
{ {
ImGui::BeginTooltip(); ImGui::BeginTooltip();
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(label.c_str()); ImGui::TextUnformatted(label.c_str());
ImGui::PopFont(); ImGui::PopFont();
ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str());
@@ -307,7 +307,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
{ {
case ROOT: case ROOT:
{ {
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(localize.get(BASIC_ROOT)); ImGui::TextUnformatted(localize.get(BASIC_ROOT));
ImGui::PopFont(); ImGui::PopFont();
@@ -328,7 +328,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
auto layer = ::item_get(model.content.layers, id); auto layer = ::item_get(model.content.layers, id);
if (!layer) if (!layer)
break; break;
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(layer->name.c_str()); ImGui::TextUnformatted(layer->name.c_str());
ImGui::PopFont(); ImGui::PopFont();
@@ -348,7 +348,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
auto nullInfo = ::item_get(model.content.nulls, id); auto nullInfo = ::item_get(model.content.nulls, id);
if (!nullInfo) if (!nullInfo)
break; break;
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(nullInfo->name.c_str()); ImGui::TextUnformatted(nullInfo->name.c_str());
ImGui::PopFont(); ImGui::PopFont();
@@ -367,7 +367,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
} }
case TRIGGER: case TRIGGER:
{ {
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE);
ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS));
ImGui::PopFont(); ImGui::PopFont();
@@ -413,7 +413,7 @@ void TimelineContext::item_child(const TimelineRow& row, int index)
overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false); overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false);
ImGui::SameLine(); ImGui::SameLine();
if (isReferenced) if (isReferenced)
ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::PushFont(resources.fonts[FONT_ITALICS], FONT_SIZE);
ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor);
ImGui::TextUnformatted(label.c_str()); ImGui::TextUnformatted(label.c_str());
ImGui::PopStyleColor(); ImGui::PopStyleColor();
+1 -1
View File
@@ -26,7 +26,7 @@ void welcome_update(Manager& manager, Resources& resources, Dialog& dialog, Task
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoScrollWithMouse)) ImGuiWindowFlags_NoScrollWithMouse))
{ {
ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); ImGui::PushFont(resources.fonts[FONT_BOLD], FONT_SIZE_LARGE);
ImGui::TextUnformatted(localize.get(LABEL_APPLICATION_NAME)); ImGui::TextUnformatted(localize.get(LABEL_APPLICATION_NAME));
ImGui::PopFont(); ImGui::PopFont();