BitmapFont.cpp 14 KB

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