GFontDatabase.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <LibCore/CDirIterator.h>
  2. #include <LibGUI/GFontDatabase.h>
  3. #include <LibDraw/Font.h>
  4. #include <dirent.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. static GFontDatabase* s_the;
  8. GFontDatabase& GFontDatabase::the()
  9. {
  10. if (!s_the)
  11. s_the = new GFontDatabase;
  12. return *s_the;
  13. }
  14. GFontDatabase::GFontDatabase()
  15. {
  16. CDirIterator di("/res/fonts", CDirIterator::SkipDots);
  17. if (di.has_error()) {
  18. fprintf(stderr, "CDirIterator: %s\n", di.error_string());
  19. exit(1);
  20. }
  21. while (di.has_next()) {
  22. String name = di.next_path();
  23. auto path = String::format("/res/fonts/%s", name.characters());
  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. }
  33. GFontDatabase::~GFontDatabase()
  34. {
  35. }
  36. void GFontDatabase::for_each_font(Function<void(const StringView&)> callback)
  37. {
  38. for (auto& it : m_name_to_metadata) {
  39. callback(it.key);
  40. }
  41. }
  42. void GFontDatabase::for_each_fixed_width_font(Function<void(const StringView&)> callback)
  43. {
  44. for (auto& it : m_name_to_metadata) {
  45. if (it.value.is_fixed_width)
  46. callback(it.key);
  47. }
  48. }
  49. RefPtr<Font> GFontDatabase::get_by_name(const StringView& name)
  50. {
  51. auto it = m_name_to_metadata.find(name);
  52. if (it == m_name_to_metadata.end())
  53. return nullptr;
  54. return Font::load_from_file((*it).value.path);
  55. }