BitmapFont.cpp 14 KB

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