BitmapFont.cpp 16 KB

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