BitmapFont.cpp 15 KB

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