Font.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. * Copyright (c) 2020, Srimanta Barua <srimanta.barua1@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "AK/ByteBuffer.h"
  27. #include <AK/Checked.h>
  28. #include <AK/LogStream.h>
  29. #include <AK/Utf32View.h>
  30. #include <AK/Utf8View.h>
  31. #include <LibCore/File.h>
  32. #include <LibTTF/Cmap.h>
  33. #include <LibTTF/Font.h>
  34. #include <LibTTF/Glyf.h>
  35. #include <LibTTF/Tables.h>
  36. #include <math.h>
  37. namespace TTF {
  38. u16 be_u16(const u8* ptr);
  39. u32 be_u32(const u8* ptr);
  40. i16 be_i16(const u8* ptr);
  41. float be_fword(const u8* ptr);
  42. u32 tag_from_str(const char* str);
  43. u16 be_u16(const u8* ptr)
  44. {
  45. return (((u16)ptr[0]) << 8) | ((u16)ptr[1]);
  46. }
  47. u32 be_u32(const u8* ptr)
  48. {
  49. return (((u32)ptr[0]) << 24) | (((u32)ptr[1]) << 16) | (((u32)ptr[2]) << 8) | ((u32)ptr[3]);
  50. }
  51. i16 be_i16(const u8* ptr)
  52. {
  53. return (((i16)ptr[0]) << 8) | ((i16)ptr[1]);
  54. }
  55. float be_fword(const u8* ptr)
  56. {
  57. return (float)be_i16(ptr) / (float)(1 << 14);
  58. }
  59. u32 tag_from_str(const char* str)
  60. {
  61. return be_u32((const u8*)str);
  62. }
  63. Optional<Head> Head::from_slice(const ReadonlyBytes& slice)
  64. {
  65. if (slice.size() < (size_t)Sizes::Table) {
  66. return {};
  67. }
  68. return Head(slice);
  69. }
  70. u16 Head::units_per_em() const
  71. {
  72. return be_u16(m_slice.offset_pointer((u32)Offsets::UnitsPerEM));
  73. }
  74. i16 Head::xmin() const
  75. {
  76. return be_i16(m_slice.offset_pointer((u32)Offsets::XMin));
  77. }
  78. i16 Head::ymin() const
  79. {
  80. return be_i16(m_slice.offset_pointer((u32)Offsets::YMin));
  81. }
  82. i16 Head::xmax() const
  83. {
  84. return be_i16(m_slice.offset_pointer((u32)Offsets::XMax));
  85. }
  86. i16 Head::ymax() const
  87. {
  88. return be_i16(m_slice.offset_pointer((u32)Offsets::YMax));
  89. }
  90. u16 Head::lowest_recommended_ppem() const
  91. {
  92. return be_u16(m_slice.offset_pointer((u32)Offsets::LowestRecPPEM));
  93. }
  94. IndexToLocFormat Head::index_to_loc_format() const
  95. {
  96. i16 raw = be_i16(m_slice.offset_pointer((u32)Offsets::IndexToLocFormat));
  97. switch (raw) {
  98. case 0:
  99. return IndexToLocFormat::Offset16;
  100. case 1:
  101. return IndexToLocFormat::Offset32;
  102. default:
  103. ASSERT_NOT_REACHED();
  104. }
  105. }
  106. Optional<Hhea> Hhea::from_slice(const ReadonlyBytes& slice)
  107. {
  108. if (slice.size() < (size_t)Sizes::Table) {
  109. return {};
  110. }
  111. return Hhea(slice);
  112. }
  113. i16 Hhea::ascender() const
  114. {
  115. return be_i16(m_slice.offset_pointer((u32)Offsets::Ascender));
  116. }
  117. i16 Hhea::descender() const
  118. {
  119. return be_i16(m_slice.offset_pointer((u32)Offsets::Descender));
  120. }
  121. i16 Hhea::line_gap() const
  122. {
  123. return be_i16(m_slice.offset_pointer((u32)Offsets::LineGap));
  124. }
  125. u16 Hhea::advance_width_max() const
  126. {
  127. return be_u16(m_slice.offset_pointer((u32)Offsets::AdvanceWidthMax));
  128. }
  129. u16 Hhea::number_of_h_metrics() const
  130. {
  131. return be_u16(m_slice.offset_pointer((u32)Offsets::NumberOfHMetrics));
  132. }
  133. Optional<Maxp> Maxp::from_slice(const ReadonlyBytes& slice)
  134. {
  135. if (slice.size() < (size_t)Sizes::TableV0p5) {
  136. return {};
  137. }
  138. return Maxp(slice);
  139. }
  140. u16 Maxp::num_glyphs() const
  141. {
  142. return be_u16(m_slice.offset_pointer((u32)Offsets::NumGlyphs));
  143. }
  144. Optional<Hmtx> Hmtx::from_slice(const ReadonlyBytes& slice, u32 num_glyphs, u32 number_of_h_metrics)
  145. {
  146. if (slice.size() < number_of_h_metrics * (u32)Sizes::LongHorMetric + (num_glyphs - number_of_h_metrics) * (u32)Sizes::LeftSideBearing) {
  147. return {};
  148. }
  149. return Hmtx(slice, num_glyphs, number_of_h_metrics);
  150. }
  151. Optional<Name> Name::from_slice(const ReadonlyBytes& slice)
  152. {
  153. return Name(slice);
  154. }
  155. String Name::string_for_id(NameId id) const
  156. {
  157. auto num_entries = be_u16(m_slice.offset_pointer(2));
  158. auto string_offset = be_u16(m_slice.offset_pointer(4));
  159. for (int i = 0; i < num_entries; ++i) {
  160. auto this_id = be_u16(m_slice.offset_pointer(6 + i * 12 + 6));
  161. if (this_id != (u16)id)
  162. continue;
  163. auto length = be_u16(m_slice.offset_pointer(6 + i * 12 + 8));
  164. auto offset = be_u16(m_slice.offset_pointer(6 + i * 12 + 10));
  165. return String((const char*)m_slice.offset_pointer(string_offset + offset), length);
  166. }
  167. return String::empty();
  168. }
  169. GlyphHorizontalMetrics Hmtx::get_glyph_horizontal_metrics(u32 glyph_id) const
  170. {
  171. ASSERT(glyph_id < m_num_glyphs);
  172. if (glyph_id < m_number_of_h_metrics) {
  173. auto offset = glyph_id * (u32)Sizes::LongHorMetric;
  174. u16 advance_width = be_u16(m_slice.offset_pointer(offset));
  175. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset + 2));
  176. return GlyphHorizontalMetrics {
  177. .advance_width = advance_width,
  178. .left_side_bearing = left_side_bearing,
  179. };
  180. }
  181. auto offset = m_number_of_h_metrics * (u32)Sizes::LongHorMetric + (glyph_id - m_number_of_h_metrics) * (u32)Sizes::LeftSideBearing;
  182. u16 advance_width = be_u16(m_slice.offset_pointer((m_number_of_h_metrics - 1) * (u32)Sizes::LongHorMetric));
  183. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset));
  184. return GlyphHorizontalMetrics {
  185. .advance_width = advance_width,
  186. .left_side_bearing = left_side_bearing,
  187. };
  188. }
  189. RefPtr<Font> Font::load_from_file(const StringView& path, unsigned index)
  190. {
  191. auto file_or_error = Core::File::open(String(path), Core::IODevice::ReadOnly);
  192. if (file_or_error.is_error()) {
  193. dbgln("Could not open file: {}", file_or_error.error());
  194. return nullptr;
  195. }
  196. auto file = file_or_error.value();
  197. if (!file->open(Core::IODevice::ReadOnly)) {
  198. dbgln("Could not open file");
  199. return nullptr;
  200. }
  201. auto buffer = file->read_all();
  202. return load_from_memory(buffer, index);
  203. }
  204. RefPtr<Font> Font::load_from_memory(ByteBuffer& buffer, unsigned index)
  205. {
  206. if (buffer.size() < 4) {
  207. dbgln("Font file too small");
  208. return nullptr;
  209. }
  210. u32 tag = be_u32(buffer.data());
  211. if (tag == tag_from_str("ttcf")) {
  212. // It's a font collection
  213. if (buffer.size() < (u32)Sizes::TTCHeaderV1 + sizeof(u32) * (index + 1)) {
  214. dbgln("Font file too small");
  215. return nullptr;
  216. }
  217. u32 offset = be_u32(buffer.offset_pointer((u32)Sizes::TTCHeaderV1 + sizeof(u32) * index));
  218. return load_from_offset(move(buffer), offset);
  219. }
  220. if (tag == tag_from_str("OTTO")) {
  221. dbgln("CFF fonts not supported yet");
  222. return nullptr;
  223. }
  224. if (tag != 0x00010000) {
  225. dbgln("Not a valid font");
  226. return nullptr;
  227. }
  228. return load_from_offset(move(buffer), 0);
  229. }
  230. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  231. RefPtr<Font> Font::load_from_offset(ByteBuffer&& buffer, u32 offset)
  232. {
  233. if (Checked<u32>::addition_would_overflow(offset, (u32)Sizes::OffsetTable)) {
  234. dbgln("Invalid offset in font header");
  235. return nullptr;
  236. }
  237. if (buffer.size() < offset + (u32)Sizes::OffsetTable) {
  238. dbgln("Font file too small");
  239. return nullptr;
  240. }
  241. Optional<ReadonlyBytes> opt_head_slice = {};
  242. Optional<ReadonlyBytes> opt_name_slice = {};
  243. Optional<ReadonlyBytes> opt_hhea_slice = {};
  244. Optional<ReadonlyBytes> opt_maxp_slice = {};
  245. Optional<ReadonlyBytes> opt_hmtx_slice = {};
  246. Optional<ReadonlyBytes> opt_cmap_slice = {};
  247. Optional<ReadonlyBytes> opt_loca_slice = {};
  248. Optional<ReadonlyBytes> opt_glyf_slice = {};
  249. Optional<Head> opt_head = {};
  250. Optional<Name> opt_name = {};
  251. Optional<Hhea> opt_hhea = {};
  252. Optional<Maxp> opt_maxp = {};
  253. Optional<Hmtx> opt_hmtx = {};
  254. Optional<Cmap> opt_cmap = {};
  255. Optional<Loca> opt_loca = {};
  256. auto num_tables = be_u16(buffer.offset_pointer(offset + (u32)Offsets::NumTables));
  257. if (buffer.size() < offset + (u32)Sizes::OffsetTable + num_tables * (u32)Sizes::TableRecord) {
  258. dbgln("Font file too small");
  259. return nullptr;
  260. }
  261. for (auto i = 0; i < num_tables; i++) {
  262. u32 record_offset = offset + (u32)Sizes::OffsetTable + i * (u32)Sizes::TableRecord;
  263. u32 tag = be_u32(buffer.offset_pointer(record_offset));
  264. u32 table_offset = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Offset));
  265. u32 table_length = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Length));
  266. if (Checked<u32>::addition_would_overflow(table_offset, table_length)) {
  267. dbgln("Invalid table offset/length in font.");
  268. return nullptr;
  269. }
  270. if (buffer.size() < table_offset + table_length) {
  271. dbgln("Font file too small");
  272. return nullptr;
  273. }
  274. auto buffer_here = ReadonlyBytes(buffer.offset_pointer(table_offset), table_length);
  275. // Get the table offsets we need.
  276. if (tag == tag_from_str("head")) {
  277. opt_head_slice = buffer_here;
  278. } else if (tag == tag_from_str("name")) {
  279. opt_name_slice = buffer_here;
  280. } else if (tag == tag_from_str("hhea")) {
  281. opt_hhea_slice = buffer_here;
  282. } else if (tag == tag_from_str("maxp")) {
  283. opt_maxp_slice = buffer_here;
  284. } else if (tag == tag_from_str("hmtx")) {
  285. opt_hmtx_slice = buffer_here;
  286. } else if (tag == tag_from_str("cmap")) {
  287. opt_cmap_slice = buffer_here;
  288. } else if (tag == tag_from_str("loca")) {
  289. opt_loca_slice = buffer_here;
  290. } else if (tag == tag_from_str("glyf")) {
  291. opt_glyf_slice = buffer_here;
  292. }
  293. }
  294. if (!opt_head_slice.has_value() || !(opt_head = Head::from_slice(opt_head_slice.value())).has_value()) {
  295. dbgln("Could not load Head");
  296. return nullptr;
  297. }
  298. auto head = opt_head.value();
  299. if (!opt_name_slice.has_value() || !(opt_name = Name::from_slice(opt_name_slice.value())).has_value()) {
  300. dbg() << "Could not load Name";
  301. return nullptr;
  302. }
  303. auto name = opt_name.value();
  304. if (!opt_hhea_slice.has_value() || !(opt_hhea = Hhea::from_slice(opt_hhea_slice.value())).has_value()) {
  305. dbgln("Could not load Hhea");
  306. return nullptr;
  307. }
  308. auto hhea = opt_hhea.value();
  309. if (!opt_maxp_slice.has_value() || !(opt_maxp = Maxp::from_slice(opt_maxp_slice.value())).has_value()) {
  310. dbgln("Could not load Maxp");
  311. return nullptr;
  312. }
  313. auto maxp = opt_maxp.value();
  314. if (!opt_hmtx_slice.has_value() || !(opt_hmtx = Hmtx::from_slice(opt_hmtx_slice.value(), maxp.num_glyphs(), hhea.number_of_h_metrics())).has_value()) {
  315. dbgln("Could not load Hmtx");
  316. return nullptr;
  317. }
  318. auto hmtx = opt_hmtx.value();
  319. if (!opt_cmap_slice.has_value() || !(opt_cmap = Cmap::from_slice(opt_cmap_slice.value())).has_value()) {
  320. dbgln("Could not load Cmap");
  321. return nullptr;
  322. }
  323. auto cmap = opt_cmap.value();
  324. if (!opt_loca_slice.has_value() || !(opt_loca = Loca::from_slice(opt_loca_slice.value(), maxp.num_glyphs(), head.index_to_loc_format())).has_value()) {
  325. dbgln("Could not load Loca");
  326. return nullptr;
  327. }
  328. auto loca = opt_loca.value();
  329. if (!opt_glyf_slice.has_value()) {
  330. dbgln("Could not load Glyf");
  331. return nullptr;
  332. }
  333. auto glyf = Glyf(opt_glyf_slice.value());
  334. // Select cmap table. FIXME: Do this better. Right now, just looks for platform "Windows"
  335. // and corresponding encoding "Unicode full repertoire", or failing that, "Unicode BMP"
  336. for (u32 i = 0; i < cmap.num_subtables(); i++) {
  337. auto opt_subtable = cmap.subtable(i);
  338. if (!opt_subtable.has_value()) {
  339. continue;
  340. }
  341. auto subtable = opt_subtable.value();
  342. if (subtable.platform_id() == Cmap::Subtable::Platform::Windows) {
  343. if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeFullRepertoire) {
  344. cmap.set_active_index(i);
  345. break;
  346. }
  347. if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeBMP) {
  348. cmap.set_active_index(i);
  349. break;
  350. }
  351. }
  352. }
  353. return adopt(*new Font(move(buffer), move(head), move(name), move(hhea), move(maxp), move(hmtx), move(cmap), move(loca), move(glyf)));
  354. }
  355. ScaledFontMetrics Font::metrics(float x_scale, float y_scale) const
  356. {
  357. auto ascender = m_hhea.ascender() * y_scale;
  358. auto descender = m_hhea.descender() * y_scale;
  359. auto line_gap = m_hhea.line_gap() * y_scale;
  360. auto advance_width_max = m_hhea.advance_width_max() * x_scale;
  361. return ScaledFontMetrics {
  362. .ascender = (int)roundf(ascender),
  363. .descender = (int)roundf(descender),
  364. .line_gap = (int)roundf(line_gap),
  365. .advance_width_max = (int)roundf(advance_width_max),
  366. };
  367. }
  368. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  369. ScaledGlyphMetrics Font::glyph_metrics(u32 glyph_id, float x_scale, float y_scale) const
  370. {
  371. if (glyph_id >= glyph_count()) {
  372. glyph_id = 0;
  373. }
  374. auto horizontal_metrics = m_hmtx.get_glyph_horizontal_metrics(glyph_id);
  375. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  376. auto glyph = m_glyf.glyph(glyph_offset);
  377. int ascender = glyph.ascender();
  378. int descender = glyph.descender();
  379. return ScaledGlyphMetrics {
  380. .ascender = (int)roundf(ascender * y_scale),
  381. .descender = (int)roundf(descender * y_scale),
  382. .advance_width = (int)roundf(horizontal_metrics.advance_width * x_scale),
  383. .left_side_bearing = (int)roundf(horizontal_metrics.left_side_bearing * x_scale),
  384. };
  385. }
  386. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  387. RefPtr<Gfx::Bitmap> Font::raster_glyph(u32 glyph_id, float x_scale, float y_scale) const
  388. {
  389. if (glyph_id >= glyph_count()) {
  390. glyph_id = 0;
  391. }
  392. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  393. auto glyph = m_glyf.glyph(glyph_offset);
  394. return glyph.raster(x_scale, y_scale, [&](u16 glyph_id) {
  395. if (glyph_id >= glyph_count()) {
  396. glyph_id = 0;
  397. }
  398. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  399. return m_glyf.glyph(glyph_offset);
  400. });
  401. }
  402. u32 Font::glyph_count() const
  403. {
  404. return m_maxp.num_glyphs();
  405. }
  406. u16 Font::units_per_em() const
  407. {
  408. return m_head.units_per_em();
  409. }
  410. String Font::family() const
  411. {
  412. auto string = m_name.typographic_family_name();
  413. if (!string.is_empty())
  414. return string;
  415. return m_name.family_name();
  416. }
  417. String Font::variant() const
  418. {
  419. auto string = m_name.typographic_subfamily_name();
  420. if (!string.is_empty())
  421. return string;
  422. return m_name.subfamily_name();
  423. }
  424. int ScaledFont::width(const StringView& string) const
  425. {
  426. Utf8View utf8 { string };
  427. return width(utf8);
  428. }
  429. int ScaledFont::width(const Utf8View& utf8) const
  430. {
  431. int width = 0;
  432. for (u32 codepoint : utf8) {
  433. u32 glyph_id = glyph_id_for_codepoint(codepoint);
  434. auto metrics = glyph_metrics(glyph_id);
  435. width += metrics.advance_width;
  436. }
  437. return width;
  438. }
  439. int ScaledFont::width(const Utf32View& utf32) const
  440. {
  441. int width = 0;
  442. for (size_t i = 0; i < utf32.length(); i++) {
  443. u32 glyph_id = glyph_id_for_codepoint(utf32.code_points()[i]);
  444. auto metrics = glyph_metrics(glyph_id);
  445. width += metrics.advance_width;
  446. }
  447. return width;
  448. }
  449. RefPtr<Gfx::Bitmap> ScaledFont::raster_glyph(u32 glyph_id) const
  450. {
  451. auto glyph_iterator = m_cached_glyph_bitmaps.find(glyph_id);
  452. if (glyph_iterator != m_cached_glyph_bitmaps.end())
  453. return glyph_iterator->value;
  454. auto glyph_bitmap = m_font->raster_glyph(glyph_id, m_x_scale, m_y_scale);
  455. m_cached_glyph_bitmaps.set(glyph_id, glyph_bitmap);
  456. return glyph_bitmap;
  457. }
  458. Gfx::Glyph ScaledFont::glyph(u32 code_point) const
  459. {
  460. auto id = glyph_id_for_codepoint(code_point);
  461. auto bitmap = raster_glyph(id);
  462. return Gfx::Glyph(bitmap);
  463. }
  464. u8 ScaledFont::glyph_width(size_t code_point) const
  465. {
  466. auto id = glyph_id_for_codepoint(code_point);
  467. auto metrics = glyph_metrics(id);
  468. return metrics.advance_width;
  469. }
  470. int ScaledFont::glyph_or_emoji_width(u32 code_point) const
  471. {
  472. auto id = glyph_id_for_codepoint(code_point);
  473. auto metrics = glyph_metrics(id);
  474. return metrics.advance_width;
  475. }
  476. u8 ScaledFont::glyph_fixed_width() const
  477. {
  478. return (u8)m_x_scale;
  479. }
  480. }