BitmapFont.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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(name)
  108. , m_family(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(const u8* data)
  160. {
  161. auto& 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((const u8*)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. if (stream.handle_any_error())
  224. return false;
  225. return true;
  226. }
  227. Glyph BitmapFont::glyph(u32 code_point) const
  228. {
  229. // Note: Until all fonts support the 0xFFFD replacement
  230. // character, fall back to painting '?' if necessary.
  231. auto index = glyph_index(code_point).value_or('?');
  232. auto width = m_glyph_widths[index];
  233. return Glyph(
  234. GlyphBitmap(m_rows, index * m_glyph_height, { width, m_glyph_height }),
  235. 0,
  236. width,
  237. m_glyph_height);
  238. }
  239. Glyph BitmapFont::raw_glyph(u32 code_point) const
  240. {
  241. auto width = m_glyph_widths[code_point];
  242. return Glyph(
  243. GlyphBitmap(m_rows, code_point * m_glyph_height, { width, m_glyph_height }),
  244. 0,
  245. width,
  246. m_glyph_height);
  247. }
  248. Optional<size_t> BitmapFont::glyph_index(u32 code_point) const
  249. {
  250. auto index = code_point / 256;
  251. if (index >= m_range_indices.size())
  252. return {};
  253. if (!m_range_indices[index].has_value())
  254. return {};
  255. return m_range_indices[index].value() * 256 + code_point % 256;
  256. }
  257. bool BitmapFont::contains_glyph(u32 code_point) const
  258. {
  259. auto index = glyph_index(code_point);
  260. return index.has_value() && m_glyph_widths[index.value()] > 0;
  261. }
  262. u8 BitmapFont::glyph_width(u32 code_point) const
  263. {
  264. if (is_ascii(code_point) && !is_ascii_printable(code_point))
  265. return 0;
  266. auto index = glyph_index(code_point);
  267. return m_fixed_width || !index.has_value() ? m_glyph_width : m_glyph_widths[index.value()];
  268. }
  269. int BitmapFont::glyph_or_emoji_width_for_variable_width_font(u32 code_point) const
  270. {
  271. // FIXME: This is a hack in lieu of proper code point identification.
  272. // 0xFFFF is arbitrary but also the end of the Basic Multilingual Plane.
  273. if (code_point < 0xFFFF) {
  274. auto index = glyph_index(code_point);
  275. if (!index.has_value())
  276. return glyph_width(0xFFFD);
  277. if (m_glyph_widths[index.value()] > 0)
  278. return glyph_width(code_point);
  279. return glyph_width(0xFFFD);
  280. }
  281. auto* emoji = Emoji::emoji_for_code_point(code_point);
  282. if (emoji == nullptr)
  283. return glyph_width(0xFFFD);
  284. return emoji->size().width();
  285. }
  286. int BitmapFont::width(StringView view) const { return unicode_view_width(Utf8View(view)); }
  287. int BitmapFont::width(Utf8View const& view) const { return unicode_view_width(view); }
  288. int BitmapFont::width(Utf32View const& view) const { return unicode_view_width(view); }
  289. template<typename T>
  290. ALWAYS_INLINE int BitmapFont::unicode_view_width(T const& view) const
  291. {
  292. if (view.is_empty())
  293. return 0;
  294. bool first = true;
  295. int width = 0;
  296. int longest_width = 0;
  297. for (u32 code_point : view) {
  298. if (code_point == '\n' || code_point == '\r') {
  299. first = true;
  300. longest_width = max(width, longest_width);
  301. width = 0;
  302. continue;
  303. }
  304. if (!first)
  305. width += glyph_spacing();
  306. first = false;
  307. width += glyph_or_emoji_width(code_point);
  308. }
  309. longest_width = max(width, longest_width);
  310. return longest_width;
  311. }
  312. String BitmapFont::qualified_name() const
  313. {
  314. return String::formatted("{} {} {}", family(), presentation_size(), weight());
  315. }
  316. String BitmapFont::variant() const
  317. {
  318. StringBuilder builder;
  319. builder.append(weight_to_name(weight()));
  320. if (slope()) {
  321. if (builder.string_view() == "Regular"sv)
  322. builder.clear();
  323. else
  324. builder.append(" ");
  325. builder.append(slope_to_name(slope()));
  326. }
  327. return builder.to_string();
  328. }
  329. Font const& Font::bold_variant() const
  330. {
  331. if (m_bold_variant)
  332. return *m_bold_variant;
  333. m_bold_variant = Gfx::FontDatabase::the().get(family(), presentation_size(), 700);
  334. if (!m_bold_variant)
  335. m_bold_variant = this;
  336. return *m_bold_variant;
  337. }
  338. FontMetrics Font::metrics(u32 code_point) const
  339. {
  340. return FontMetrics {
  341. .size = (float)presentation_size(),
  342. .x_height = (float)x_height(),
  343. .glyph_width = (float)glyph_width(code_point),
  344. .glyph_spacing = (float)glyph_spacing(),
  345. };
  346. }
  347. }