FontFamily.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "FontFamily.h"
  2. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  3. #include "../../../Include/RmlUi/Core/Math.h"
  4. #include "FontFace.h"
  5. #include <limits.h>
  6. namespace Rml {
  7. FontFamily::FontFamily(const String& name) : name(name) {}
  8. FontFamily::~FontFamily()
  9. {
  10. // Multiple face entries may share memory within a single font family, although only one of them owns it. Here we make sure that all the face
  11. // destructors are run before all the memory is released. This way we don't leave any hanging references to invalidated memory.
  12. for (FontFaceEntry& entry : font_faces)
  13. entry.face.reset();
  14. }
  15. FontFaceHandleDefault* FontFamily::GetFaceHandle(Style::FontStyle style, Style::FontWeight weight, int size)
  16. {
  17. int best_dist = INT_MAX;
  18. FontFace* matching_face = nullptr;
  19. for (size_t i = 0; i < font_faces.size(); i++)
  20. {
  21. FontFace* face = font_faces[i].face.get();
  22. if (face->GetStyle() == style)
  23. {
  24. const int dist = Math::Absolute((int)face->GetWeight() - (int)weight);
  25. if (dist == 0)
  26. {
  27. // Direct match for weight, break the loop early.
  28. matching_face = face;
  29. break;
  30. }
  31. else if (dist < best_dist)
  32. {
  33. // Best match so far for weight, store the face and dist.
  34. matching_face = face;
  35. best_dist = dist;
  36. }
  37. }
  38. }
  39. if (!matching_face)
  40. return nullptr;
  41. return matching_face->GetHandle(size, true);
  42. }
  43. FontFace* FontFamily::AddFace(FontFaceHandleFreetype ft_face, Style::FontStyle style, Style::FontWeight weight, UniquePtr<byte[]> face_memory)
  44. {
  45. auto face = MakeUnique<FontFace>(ft_face, style, weight);
  46. FontFace* result = face.get();
  47. font_faces.push_back(FontFaceEntry{std::move(face), std::move(face_memory)});
  48. return result;
  49. }
  50. void FontFamily::ReleaseFontResources()
  51. {
  52. for (auto& entry : font_faces)
  53. entry.face->ReleaseFontResources();
  54. }
  55. } // namespace Rml