FontCache.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedFlyString.h>
  7. #include <LibGfx/Font/Font.h>
  8. #include <LibWeb/FontCache.h>
  9. FontCache& FontCache::the()
  10. {
  11. static FontCache cache;
  12. return cache;
  13. }
  14. RefPtr<Gfx::Font const> FontCache::get(FontSelector const& font_selector) const
  15. {
  16. auto cached_font = m_fonts.get(font_selector);
  17. if (cached_font.has_value())
  18. return cached_font.value();
  19. return nullptr;
  20. }
  21. NonnullRefPtr<Gfx::Font const> FontCache::scaled_font(Gfx::Font const& font, float scale_factor)
  22. {
  23. auto device_font_pt_size = font.point_size() * scale_factor;
  24. FontSelector font_selector = { FlyString::from_deprecated_fly_string(font.family()).release_value_but_fixme_should_propagate_errors(), device_font_pt_size, font.weight(), font.width(), font.slope() };
  25. if (auto cached_font = FontCache::the().get(font_selector)) {
  26. return *cached_font;
  27. }
  28. if (auto font_with_device_pt_size = font.with_size(device_font_pt_size)) {
  29. set(font_selector, *font_with_device_pt_size);
  30. return font_with_device_pt_size.release_nonnull();
  31. }
  32. return font;
  33. }
  34. void FontCache::set(FontSelector const& font_selector, NonnullRefPtr<Gfx::Font const> font)
  35. {
  36. m_fonts.set(font_selector, move(font));
  37. }