GFontDatabase.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <LibGUI/GFontDatabase.h>
  2. #include <SharedGraphics/Font.h>
  3. #include <dirent.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. static GFontDatabase* s_the;
  7. GFontDatabase& GFontDatabase::the()
  8. {
  9. if (!s_the)
  10. s_the = new GFontDatabase;
  11. return *s_the;
  12. }
  13. GFontDatabase::GFontDatabase()
  14. {
  15. DIR* dirp = opendir("/res/fonts");
  16. if (!dirp) {
  17. perror("opendir");
  18. exit(1);
  19. }
  20. while (auto* de = readdir(dirp)) {
  21. if (de->d_name[0] == '.')
  22. continue;
  23. auto path = String::format("/res/fonts/%s", de->d_name);
  24. if (auto font = Font::load_from_file(path)) {
  25. Metadata metadata;
  26. metadata.path = path;
  27. metadata.glyph_height = font->glyph_height();
  28. metadata.is_fixed_width = font->is_fixed_width();
  29. m_name_to_metadata.set(font->name(), move(metadata));
  30. }
  31. }
  32. closedir(dirp);
  33. }
  34. GFontDatabase::~GFontDatabase()
  35. {
  36. }
  37. void GFontDatabase::for_each_font(Function<void(const String&)> callback)
  38. {
  39. for (auto& it : m_name_to_metadata) {
  40. callback(it.key);
  41. }
  42. }
  43. void GFontDatabase::for_each_fixed_width_font(Function<void(const String&)> callback)
  44. {
  45. for (auto& it : m_name_to_metadata) {
  46. if (it.value.is_fixed_width)
  47. callback(it.key);
  48. }
  49. }
  50. RetainPtr<Font> GFontDatabase::get_by_name(const String& name)
  51. {
  52. auto it = m_name_to_metadata.find(name);
  53. if (it == m_name_to_metadata.end())
  54. return nullptr;
  55. return Font::load_from_file((*it).value.path);
  56. }