BitmapFont.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 file = TRY(Core::MappedFile::map(path));
  217. auto font = TRY(load_from_memory((u8 const*)file->data()));
  218. font->m_mapped_file = file;
  219. return font;
  220. }
  221. ErrorOr<void> BitmapFont::write_to_file(DeprecatedString const& path)
  222. {
  223. FontFileHeader header;
  224. memset(&header, 0, sizeof(FontFileHeader));
  225. memcpy(header.magic, "!Fnt", 4);
  226. header.glyph_width = m_glyph_width;
  227. header.glyph_height = m_glyph_height;
  228. header.range_mask_size = m_range_mask_size;
  229. header.baseline = m_baseline;
  230. header.mean_line = m_mean_line;
  231. header.is_variable_width = !m_fixed_width;
  232. header.glyph_spacing = m_glyph_spacing;
  233. header.presentation_size = m_presentation_size;
  234. header.weight = m_weight;
  235. header.slope = m_slope;
  236. memcpy(header.name, m_name.characters(), min(m_name.length(), sizeof(header.name) - 1));
  237. memcpy(header.family, m_family.characters(), min(m_family.length(), sizeof(header.family) - 1));
  238. auto stream = TRY(Core::File::open(path, Core::File::OpenMode::Write));
  239. size_t bytes_per_glyph = sizeof(u32) * m_glyph_height;
  240. TRY(stream->write_until_depleted({ &header, sizeof(header) }));
  241. TRY(stream->write_until_depleted({ m_range_mask, m_range_mask_size }));
  242. TRY(stream->write_until_depleted({ m_rows, m_glyph_count * bytes_per_glyph }));
  243. TRY(stream->write_until_depleted({ m_glyph_widths, m_glyph_count }));
  244. return {};
  245. }
  246. Glyph BitmapFont::glyph(u32 code_point) const
  247. {
  248. // Note: Until all fonts support the 0xFFFD replacement
  249. // character, fall back to painting '?' if necessary.
  250. auto index = glyph_index(code_point).value_or('?');
  251. auto width = m_glyph_widths[index];
  252. return Glyph(
  253. GlyphBitmap(m_rows, index * m_glyph_height, { width, m_glyph_height }),
  254. 0,
  255. width,
  256. m_glyph_height);
  257. }
  258. Glyph BitmapFont::raw_glyph(u32 code_point) const
  259. {
  260. auto width = m_glyph_widths[code_point];
  261. return Glyph(
  262. GlyphBitmap(m_rows, code_point * m_glyph_height, { width, m_glyph_height }),
  263. 0,
  264. width,
  265. m_glyph_height);
  266. }
  267. Optional<size_t> BitmapFont::glyph_index(u32 code_point) const
  268. {
  269. auto index = code_point / 256;
  270. if (index >= m_range_indices.size())
  271. return {};
  272. if (!m_range_indices[index].has_value())
  273. return {};
  274. return m_range_indices[index].value() * 256 + code_point % 256;
  275. }
  276. bool BitmapFont::contains_glyph(u32 code_point) const
  277. {
  278. auto index = glyph_index(code_point);
  279. return index.has_value() && m_glyph_widths[index.value()] > 0;
  280. }
  281. float BitmapFont::glyph_width(u32 code_point) const
  282. {
  283. if (is_ascii(code_point) && !is_ascii_printable(code_point))
  284. return 0;
  285. auto index = glyph_index(code_point);
  286. return m_fixed_width || !index.has_value() ? m_glyph_width : m_glyph_widths[index.value()];
  287. }
  288. template<typename CodePointIterator>
  289. static float glyph_or_emoji_width_impl(BitmapFont const& font, CodePointIterator& it)
  290. {
  291. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it))
  292. return font.pixel_size() * emoji->width() / emoji->height();
  293. if (font.is_fixed_width())
  294. return font.glyph_fixed_width();
  295. return font.glyph_width(*it);
  296. }
  297. float BitmapFont::glyph_or_emoji_width(Utf8CodePointIterator& it) const
  298. {
  299. return glyph_or_emoji_width_impl(*this, it);
  300. }
  301. float BitmapFont::glyph_or_emoji_width(Utf32CodePointIterator& it) const
  302. {
  303. return glyph_or_emoji_width_impl(*this, it);
  304. }
  305. float BitmapFont::width(StringView view) const { return unicode_view_width(Utf8View(view)); }
  306. float BitmapFont::width(Utf8View const& view) const { return unicode_view_width(view); }
  307. float BitmapFont::width(Utf32View const& view) const { return unicode_view_width(view); }
  308. template<typename T>
  309. ALWAYS_INLINE int BitmapFont::unicode_view_width(T const& view) const
  310. {
  311. if (view.is_empty())
  312. return 0;
  313. bool first = true;
  314. int width = 0;
  315. int longest_width = 0;
  316. for (auto it = view.begin(); it != view.end(); ++it) {
  317. auto code_point = *it;
  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(it);
  328. }
  329. longest_width = max(width, longest_width);
  330. return longest_width;
  331. }
  332. DeprecatedString BitmapFont::qualified_name() const
  333. {
  334. return DeprecatedString::formatted("{} {} {} {}", family(), presentation_size(), weight(), slope());
  335. }
  336. DeprecatedString 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_deprecated_string();
  348. }
  349. RefPtr<Font> BitmapFont::with_size(float point_size) const
  350. {
  351. return Gfx::FontDatabase::the().get(family(), point_size, weight(), width(), slope());
  352. }
  353. Font const& Font::bold_variant() const
  354. {
  355. if (m_bold_variant)
  356. return *m_bold_variant;
  357. m_bold_variant = Gfx::FontDatabase::the().get(family(), presentation_size(), 700, Gfx::FontWidth::Normal, 0);
  358. if (!m_bold_variant)
  359. m_bold_variant = this;
  360. return *m_bold_variant;
  361. }
  362. FontPixelMetrics BitmapFont::pixel_metrics() const
  363. {
  364. return FontPixelMetrics {
  365. .size = (float)pixel_size(),
  366. .x_height = (float)x_height(),
  367. .advance_of_ascii_zero = (float)glyph_width('0'),
  368. .glyph_spacing = (float)glyph_spacing(),
  369. .ascent = (float)m_baseline,
  370. .descent = (float)(m_glyph_height - m_baseline),
  371. .line_gap = Gfx::Painter::LINE_SPACING,
  372. };
  373. }
  374. }