GFontDatabase.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <AK/QuickSort.h>
  2. #include <LibCore/CDirIterator.h>
  3. #include <LibDraw/Font.h>
  4. #include <LibGUI/GFontDatabase.h>
  5. #include <dirent.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. static GFontDatabase* s_the;
  9. GFontDatabase& GFontDatabase::the()
  10. {
  11. if (!s_the)
  12. s_the = new GFontDatabase;
  13. return *s_the;
  14. }
  15. GFontDatabase::GFontDatabase()
  16. {
  17. CDirIterator di("/res/fonts", CDirIterator::SkipDots);
  18. if (di.has_error()) {
  19. fprintf(stderr, "CDirIterator: %s\n", di.error_string());
  20. exit(1);
  21. }
  22. while (di.has_next()) {
  23. String name = di.next_path();
  24. auto path = String::format("/res/fonts/%s", name.characters());
  25. if (auto font = Font::load_from_file(path)) {
  26. Metadata metadata;
  27. metadata.path = path;
  28. metadata.glyph_height = font->glyph_height();
  29. metadata.is_fixed_width = font->is_fixed_width();
  30. m_name_to_metadata.set(font->name(), move(metadata));
  31. }
  32. }
  33. }
  34. GFontDatabase::~GFontDatabase()
  35. {
  36. }
  37. void GFontDatabase::for_each_font(Function<void(const StringView&)> callback)
  38. {
  39. Vector<String> names;
  40. names.ensure_capacity(m_name_to_metadata.size());
  41. for (auto& it : m_name_to_metadata)
  42. names.append(it.key);
  43. quick_sort(names.begin(), names.end(), AK::is_less_than<String>);
  44. for (auto& name : names)
  45. callback(name);
  46. }
  47. void GFontDatabase::for_each_fixed_width_font(Function<void(const StringView&)> callback)
  48. {
  49. Vector<String> names;
  50. names.ensure_capacity(m_name_to_metadata.size());
  51. for (auto& it : m_name_to_metadata) {
  52. if (it.value.is_fixed_width)
  53. names.append(it.key);
  54. }
  55. quick_sort(names.begin(), names.end(), AK::is_less_than<String>);
  56. for (auto& name : names)
  57. callback(name);
  58. }
  59. RefPtr<Font> GFontDatabase::get_by_name(const StringView& name)
  60. {
  61. auto it = m_name_to_metadata.find(name);
  62. if (it == m_name_to_metadata.end())
  63. return nullptr;
  64. return Font::load_from_file((*it).value.path);
  65. }