BitmapFont.cpp 16 KB

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