BitmapFont.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "BitmapFont.h"
  8. #include "Emoji.h"
  9. #include <AK/BuiltinWrappers.h>
  10. #include <AK/Utf32View.h>
  11. #include <AK/Utf8View.h>
  12. #include <LibCore/File.h>
  13. #include <LibCore/Resource.h>
  14. #include <LibCore/System.h>
  15. #include <LibGfx/Font/FontDatabase.h>
  16. #include <LibGfx/Font/FontStyleMapping.h>
  17. #include <LibGfx/Painter.h>
  18. #include <string.h>
  19. namespace Gfx {
  20. struct [[gnu::packed]] FontFileHeader {
  21. char magic[4];
  22. u8 glyph_width;
  23. u8 glyph_height;
  24. u16 range_mask_size;
  25. u8 is_variable_width;
  26. u8 glyph_spacing;
  27. u8 baseline;
  28. u8 mean_line;
  29. u8 presentation_size;
  30. u16 weight;
  31. u8 slope;
  32. char name[32];
  33. char family[32];
  34. };
  35. static_assert(AssertSize<FontFileHeader, 80>());
  36. static constexpr size_t s_max_glyph_count = 0x110000;
  37. static constexpr size_t s_max_range_mask_size = s_max_glyph_count / (256 * 8);
  38. }
  39. // FIXME: We define the traits for the const FontFileHeader, because that's the one we use, and defining
  40. // Traits<T> doesn't apply to Traits<T const>. Once that's fixed, remove the const here.
  41. template<>
  42. class AK::Traits<Gfx::FontFileHeader const> : public GenericTraits<Gfx::FontFileHeader const> {
  43. public:
  44. static constexpr bool is_trivially_serializable() { return true; }
  45. };
  46. namespace Gfx {
  47. NonnullRefPtr<Font> BitmapFont::clone() const
  48. {
  49. return MUST(try_clone());
  50. }
  51. ErrorOr<NonnullRefPtr<Font>> BitmapFont::try_clone() const
  52. {
  53. auto new_range_mask = TRY(Core::System::allocate(m_range_mask.size(), 1));
  54. m_range_mask.copy_to(new_range_mask);
  55. size_t bytes_per_glyph = sizeof(u32) * glyph_height();
  56. auto new_rows = TRY(Core::System::allocate(m_glyph_count, bytes_per_glyph));
  57. m_rows.copy_to(new_rows);
  58. auto new_widths = TRY(Core::System::allocate(m_glyph_count, 1));
  59. m_glyph_widths.copy_to(new_widths);
  60. return TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true)));
  61. }
  62. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::create(u8 glyph_height, u8 glyph_width, bool fixed, size_t glyph_count)
  63. {
  64. glyph_count += 256 - (glyph_count % 256);
  65. glyph_count = min(glyph_count, s_max_glyph_count);
  66. size_t glyphs_per_range = 8 * 256;
  67. u16 range_mask_size = ceil_div(glyph_count, glyphs_per_range);
  68. auto new_range_mask = TRY(Core::System::allocate(range_mask_size, 1));
  69. for (size_t i = 0; i < glyph_count; i += 256) {
  70. new_range_mask[i / 256 / 8] |= 1 << (i / 256 % 8);
  71. }
  72. size_t bytes_per_glyph = sizeof(u32) * glyph_height;
  73. auto new_rows = TRY(Core::System::allocate(glyph_count, bytes_per_glyph));
  74. auto new_widths = TRY(Core::System::allocate(glyph_count, 1));
  75. return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont("Untitled"_string, "Untitled"_string, new_rows, new_widths, fixed, glyph_width, glyph_height, 1, new_range_mask, 0, 0, 0, 400, 0, true));
  76. }
  77. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::unmasked_character_set() const
  78. {
  79. auto new_range_mask = TRY(Core::System::allocate(s_max_range_mask_size, 1));
  80. constexpr u8 max_bits { 0b1111'1111 };
  81. memset(new_range_mask.data(), max_bits, s_max_range_mask_size);
  82. size_t bytes_per_glyph = sizeof(u32) * glyph_height();
  83. auto new_rows = TRY(Core::System::allocate(s_max_glyph_count, bytes_per_glyph));
  84. auto new_widths = TRY(Core::System::allocate(s_max_glyph_count, 1));
  85. for (size_t code_point = 0; code_point < s_max_glyph_count; ++code_point) {
  86. auto index = glyph_index(code_point);
  87. if (index.has_value()) {
  88. new_widths[code_point] = m_glyph_widths[index.value()];
  89. memcpy(&new_rows[code_point * bytes_per_glyph], &m_rows[index.value() * bytes_per_glyph], bytes_per_glyph);
  90. }
  91. }
  92. return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
  93. }
  94. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::masked_character_set() const
  95. {
  96. auto new_range_mask = TRY(Core::System::allocate(s_max_range_mask_size, 1));
  97. u16 new_range_mask_size { 0 };
  98. for (size_t i = 0; i < m_glyph_count; ++i) {
  99. if (m_glyph_widths[i] > 0) {
  100. new_range_mask[i / 256 / 8] |= 1 << (i / 256 % 8);
  101. if (i / 256 / 8 + 1 > new_range_mask_size)
  102. new_range_mask_size = i / 256 / 8 + 1;
  103. }
  104. }
  105. size_t new_glyph_count { 0 };
  106. for (size_t i = 0; i < new_range_mask_size; ++i) {
  107. new_glyph_count += 256 * popcount(new_range_mask[i]);
  108. }
  109. size_t bytes_per_glyph = sizeof(u32) * m_glyph_height;
  110. auto new_rows = TRY(Core::System::allocate(new_glyph_count, bytes_per_glyph));
  111. auto new_widths = TRY(Core::System::allocate(new_glyph_count, 1));
  112. for (size_t i = 0, j = 0; i < m_glyph_count; ++i) {
  113. if (!(new_range_mask[i / 256 / 8] & 1 << (i / 256 % 8))) {
  114. j++;
  115. i += 255;
  116. continue;
  117. }
  118. new_widths[i - j * 256] = m_glyph_widths[i];
  119. memcpy(&new_rows[(i - j * 256) * bytes_per_glyph], &m_rows[i * bytes_per_glyph], bytes_per_glyph);
  120. }
  121. // Now that we're done working with the range-mask memory, reduce its reported size down to what it should be.
  122. new_range_mask = { new_range_mask.data(), new_range_mask_size };
  123. return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
  124. }
  125. BitmapFont::BitmapFont(String name, String family, Bytes rows, Span<u8> widths, bool is_fixed_width, u8 glyph_width, u8 glyph_height, u8 glyph_spacing, Bytes range_mask, u8 baseline, u8 mean_line, u8 presentation_size, u16 weight, u8 slope, bool owns_arrays)
  126. : m_name(move(name))
  127. , m_family(move(family))
  128. , m_range_mask(range_mask)
  129. , m_rows(rows)
  130. , m_glyph_widths(widths)
  131. , m_glyph_width(glyph_width)
  132. , m_glyph_height(glyph_height)
  133. , m_min_glyph_width(glyph_width)
  134. , m_max_glyph_width(glyph_width)
  135. , m_glyph_spacing(glyph_spacing)
  136. , m_baseline(baseline)
  137. , m_mean_line(mean_line)
  138. , m_presentation_size(presentation_size)
  139. , m_weight(weight)
  140. , m_slope(slope)
  141. , m_fixed_width(is_fixed_width)
  142. , m_owns_arrays(owns_arrays)
  143. {
  144. update_x_height();
  145. for (size_t i = 0, index = 0; i < m_range_mask.size(); ++i) {
  146. for (size_t j = 0; j < 8; ++j) {
  147. if (m_range_mask[i] & (1 << j)) {
  148. m_glyph_count += 256;
  149. m_range_indices.append(index++);
  150. } else {
  151. m_range_indices.append({});
  152. }
  153. }
  154. }
  155. if (!m_fixed_width) {
  156. u8 maximum = 0;
  157. u8 minimum = 255;
  158. for (size_t i = 0; i < m_glyph_count; ++i) {
  159. minimum = min(minimum, m_glyph_widths[i]);
  160. maximum = max(maximum, m_glyph_widths[i]);
  161. }
  162. m_min_glyph_width = minimum;
  163. m_max_glyph_width = max(maximum, m_glyph_width);
  164. }
  165. }
  166. BitmapFont::~BitmapFont()
  167. {
  168. if (m_owns_arrays) {
  169. free(m_glyph_widths.data());
  170. free(m_rows.data());
  171. free(m_range_mask.data());
  172. }
  173. }
  174. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_stream(FixedMemoryStream& stream)
  175. {
  176. auto& header = *TRY(stream.read_in_place<FontFileHeader const>());
  177. if (memcmp(header.magic, "!Fnt", 4))
  178. return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Incompatible header");
  179. if (header.name[sizeof(header.name) - 1] != '\0')
  180. return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Nonnull-terminated name");
  181. if (header.family[sizeof(header.family) - 1] != '\0')
  182. return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Nonnull-terminated family");
  183. size_t bytes_per_glyph = sizeof(u32) * header.glyph_height;
  184. size_t glyph_count { 0 };
  185. // FIXME: These ReadonlyFoo -> Foo casts are awkward, and only needed because BitmapFont is
  186. // sometimes editable and sometimes not. Splitting it into editable/non-editable classes
  187. // would make this a lot cleaner.
  188. ReadonlyBytes readonly_range_mask = TRY(stream.read_in_place<u8 const>(header.range_mask_size));
  189. Bytes range_mask { const_cast<u8*>(readonly_range_mask.data()), readonly_range_mask.size() };
  190. for (size_t i = 0; i < header.range_mask_size; ++i)
  191. glyph_count += 256 * popcount(range_mask[i]);
  192. ReadonlyBytes readonly_rows = TRY(stream.read_in_place<u8 const>(glyph_count * bytes_per_glyph));
  193. Bytes rows { const_cast<u8*>(readonly_rows.data()), readonly_rows.size() };
  194. ReadonlySpan<u8> readonly_widths = TRY(stream.read_in_place<u8 const>(glyph_count));
  195. Span<u8> widths { const_cast<u8*>(readonly_widths.data()), readonly_widths.size() };
  196. if (!stream.is_eof())
  197. return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Trailing data in file");
  198. auto name = TRY(String::from_utf8(ReadonlyBytes { header.name, strlen(header.name) }));
  199. auto family = TRY(String::from_utf8(ReadonlyBytes { header.family, strlen(header.family) }));
  200. auto font = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(move(name), move(family), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, range_mask, header.baseline, header.mean_line, header.presentation_size, header.weight, header.slope)));
  201. return font;
  202. }
  203. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_resource(NonnullRefPtr<Core::Resource> resource)
  204. {
  205. auto stream = resource->stream();
  206. auto font = TRY(try_load_from_stream(stream));
  207. font->m_owned_data = move(resource);
  208. return font;
  209. }
  210. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_mapped_file(NonnullOwnPtr<Core::MappedFile> mapped_file)
  211. {
  212. auto font = TRY(try_load_from_stream(*mapped_file));
  213. font->m_owned_data = move(mapped_file);
  214. return font;
  215. }
  216. NonnullRefPtr<BitmapFont> BitmapFont::load_from_uri(StringView uri)
  217. {
  218. return MUST(try_load_from_uri(uri));
  219. }
  220. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_uri(StringView uri)
  221. {
  222. return try_load_from_resource(TRY(Core::Resource::load_from_uri(uri)));
  223. }
  224. RefPtr<BitmapFont> BitmapFont::load_from_file(DeprecatedString const& path)
  225. {
  226. return MUST(try_load_from_file(move(path)));
  227. }
  228. ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_file(DeprecatedString const& path)
  229. {
  230. auto mapped_file = TRY(Core::MappedFile::map(path));
  231. return try_load_from_mapped_file(move(mapped_file));
  232. }
  233. ErrorOr<void> BitmapFont::write_to_file(DeprecatedString const& path)
  234. {
  235. auto stream = TRY(Core::File::open(path, Core::File::OpenMode::Write));
  236. TRY(write_to_file(move(stream)));
  237. return {};
  238. }
  239. ErrorOr<void> BitmapFont::write_to_file(NonnullOwnPtr<Core::File> file)
  240. {
  241. FontFileHeader header;
  242. memset(&header, 0, sizeof(FontFileHeader));
  243. memcpy(header.magic, "!Fnt", 4);
  244. header.glyph_width = m_glyph_width;
  245. header.glyph_height = m_glyph_height;
  246. header.range_mask_size = m_range_mask.size();
  247. header.baseline = m_baseline;
  248. header.mean_line = m_mean_line;
  249. header.is_variable_width = !m_fixed_width;
  250. header.glyph_spacing = m_glyph_spacing;
  251. header.presentation_size = m_presentation_size;
  252. header.weight = m_weight;
  253. header.slope = m_slope;
  254. memcpy(header.name, m_name.bytes().data(), min(m_name.bytes().size(), sizeof(header.name) - 1));
  255. memcpy(header.family, m_family.bytes().data(), min(m_family.bytes().size(), sizeof(header.family) - 1));
  256. TRY(file->write_until_depleted({ &header, sizeof(header) }));
  257. TRY(file->write_until_depleted(m_range_mask));
  258. TRY(file->write_until_depleted(m_rows));
  259. TRY(file->write_until_depleted(m_glyph_widths));
  260. return {};
  261. }
  262. Glyph BitmapFont::glyph(u32 code_point) const
  263. {
  264. // Note: Until all fonts support the 0xFFFD replacement
  265. // character, fall back to painting '?' if necessary.
  266. auto index = glyph_index(code_point).value_or('?');
  267. auto width = m_glyph_widths[index];
  268. auto glyph_byte_count = m_glyph_height * GlyphBitmap::bytes_per_row();
  269. return Glyph(
  270. GlyphBitmap(m_rows.slice(index * glyph_byte_count, glyph_byte_count), { width, m_glyph_height }),
  271. 0,
  272. width,
  273. m_glyph_height);
  274. }
  275. Glyph BitmapFont::raw_glyph(u32 code_point) const
  276. {
  277. auto width = m_glyph_widths[code_point];
  278. auto glyph_byte_count = m_glyph_height * GlyphBitmap::bytes_per_row();
  279. return Glyph(
  280. GlyphBitmap(m_rows.slice(code_point * glyph_byte_count, glyph_byte_count), { width, m_glyph_height }),
  281. 0,
  282. width,
  283. m_glyph_height);
  284. }
  285. Optional<size_t> BitmapFont::glyph_index(u32 code_point) const
  286. {
  287. auto index = code_point / 256;
  288. if (index >= m_range_indices.size())
  289. return {};
  290. if (!m_range_indices[index].has_value())
  291. return {};
  292. return m_range_indices[index].value() * 256 + code_point % 256;
  293. }
  294. bool BitmapFont::contains_glyph(u32 code_point) const
  295. {
  296. auto index = glyph_index(code_point);
  297. return index.has_value() && m_glyph_widths[index.value()] > 0;
  298. }
  299. float BitmapFont::glyph_width(u32 code_point) const
  300. {
  301. if (is_ascii(code_point) && !is_ascii_printable(code_point))
  302. return 0;
  303. auto index = glyph_index(code_point);
  304. return m_fixed_width || !index.has_value() ? m_glyph_width : m_glyph_widths[index.value()];
  305. }
  306. template<typename CodePointIterator>
  307. static float glyph_or_emoji_width_impl(BitmapFont const& font, CodePointIterator& it)
  308. {
  309. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it))
  310. return font.pixel_size() * emoji->width() / emoji->height();
  311. if (font.is_fixed_width())
  312. return font.glyph_fixed_width();
  313. return font.glyph_width(*it);
  314. }
  315. float BitmapFont::glyph_or_emoji_width(Utf8CodePointIterator& it) const
  316. {
  317. return glyph_or_emoji_width_impl(*this, it);
  318. }
  319. float BitmapFont::glyph_or_emoji_width(Utf32CodePointIterator& it) const
  320. {
  321. return glyph_or_emoji_width_impl(*this, it);
  322. }
  323. int BitmapFont::width_rounded_up(StringView view) const
  324. {
  325. return static_cast<int>(ceilf(width(view)));
  326. }
  327. float BitmapFont::width(StringView view) const { return unicode_view_width(Utf8View(view)); }
  328. float BitmapFont::width(Utf8View const& view) const { return unicode_view_width(view); }
  329. float BitmapFont::width(Utf32View const& view) const { return unicode_view_width(view); }
  330. template<typename T>
  331. ALWAYS_INLINE int BitmapFont::unicode_view_width(T const& view) const
  332. {
  333. if (view.is_empty())
  334. return 0;
  335. bool first = true;
  336. int width = 0;
  337. int longest_width = 0;
  338. for (auto it = view.begin(); it != view.end(); ++it) {
  339. auto code_point = *it;
  340. if (code_point == '\n' || code_point == '\r') {
  341. first = true;
  342. longest_width = max(width, longest_width);
  343. width = 0;
  344. continue;
  345. }
  346. if (!first)
  347. width += glyph_spacing();
  348. first = false;
  349. width += glyph_or_emoji_width(it);
  350. }
  351. longest_width = max(width, longest_width);
  352. return longest_width;
  353. }
  354. String BitmapFont::qualified_name() const
  355. {
  356. return MUST(String::formatted("{} {} {} {}", family(), presentation_size(), weight(), slope()));
  357. }
  358. String BitmapFont::variant() const
  359. {
  360. StringBuilder builder;
  361. builder.append(weight_to_name(weight()));
  362. if (slope() != 0) {
  363. if (builder.string_view() == "Regular"sv)
  364. builder.clear();
  365. else
  366. builder.append(' ');
  367. builder.append(slope_to_name(slope()));
  368. }
  369. return MUST(builder.to_string());
  370. }
  371. RefPtr<Font> BitmapFont::with_size(float point_size) const
  372. {
  373. return Gfx::FontDatabase::the().get(family(), point_size, weight(), width(), slope());
  374. }
  375. Font const& Font::bold_variant() const
  376. {
  377. if (m_bold_variant)
  378. return *m_bold_variant;
  379. m_bold_variant = Gfx::FontDatabase::the().get(family(), presentation_size(), 700, Gfx::FontWidth::Normal, 0);
  380. if (!m_bold_variant)
  381. m_bold_variant = this;
  382. return *m_bold_variant;
  383. }
  384. FontPixelMetrics BitmapFont::pixel_metrics() const
  385. {
  386. return FontPixelMetrics {
  387. .size = (float)pixel_size(),
  388. .x_height = (float)x_height(),
  389. .advance_of_ascii_zero = (float)glyph_width('0'),
  390. .glyph_spacing = (float)glyph_spacing(),
  391. .ascent = (float)m_baseline,
  392. .descent = (float)(m_glyph_height - m_baseline),
  393. .line_gap = Gfx::Painter::LINE_SPACING,
  394. };
  395. }
  396. }