Font.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. GlyphHorizontalMetrics Hmtx::get_glyph_horizontal_metrics(u32 glyph_id) const
  152. {
  153. ASSERT(glyph_id < m_num_glyphs);
  154. if (glyph_id < m_number_of_h_metrics) {
  155. auto offset = glyph_id * (u32)Sizes::LongHorMetric;
  156. u16 advance_width = be_u16(m_slice.offset_pointer(offset));
  157. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset + 2));
  158. return GlyphHorizontalMetrics {
  159. .advance_width = advance_width,
  160. .left_side_bearing = left_side_bearing,
  161. };
  162. }
  163. auto offset = m_number_of_h_metrics * (u32)Sizes::LongHorMetric + (glyph_id - m_number_of_h_metrics) * (u32)Sizes::LeftSideBearing;
  164. u16 advance_width = be_u16(m_slice.offset_pointer((m_number_of_h_metrics - 1) * (u32)Sizes::LongHorMetric));
  165. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset));
  166. return GlyphHorizontalMetrics {
  167. .advance_width = advance_width,
  168. .left_side_bearing = left_side_bearing,
  169. };
  170. }
  171. RefPtr<Font> Font::load_from_file(const StringView& path, unsigned index)
  172. {
  173. auto file_or_error = Core::File::open(String(path), Core::IODevice::ReadOnly);
  174. if (file_or_error.is_error()) {
  175. dbgln("Could not open file: {}", file_or_error.error());
  176. return nullptr;
  177. }
  178. auto file = file_or_error.value();
  179. if (!file->open(Core::IODevice::ReadOnly)) {
  180. dbgln("Could not open file");
  181. return nullptr;
  182. }
  183. auto buffer = file->read_all();
  184. return load_from_memory(buffer, index);
  185. }
  186. RefPtr<Font> Font::load_from_memory(ByteBuffer& buffer, unsigned index)
  187. {
  188. if (buffer.size() < 4) {
  189. dbgln("Font file too small");
  190. return nullptr;
  191. }
  192. u32 tag = be_u32(buffer.data());
  193. if (tag == tag_from_str("ttcf")) {
  194. // It's a font collection
  195. if (buffer.size() < (u32)Sizes::TTCHeaderV1 + sizeof(u32) * (index + 1)) {
  196. dbgln("Font file too small");
  197. return nullptr;
  198. }
  199. u32 offset = be_u32(buffer.offset_pointer((u32)Sizes::TTCHeaderV1 + sizeof(u32) * index));
  200. return load_from_offset(move(buffer), offset);
  201. }
  202. if (tag == tag_from_str("OTTO")) {
  203. dbgln("CFF fonts not supported yet");
  204. return nullptr;
  205. }
  206. if (tag != 0x00010000) {
  207. dbgln("Not a valid font");
  208. return nullptr;
  209. }
  210. return load_from_offset(move(buffer), 0);
  211. }
  212. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  213. RefPtr<Font> Font::load_from_offset(ByteBuffer&& buffer, u32 offset)
  214. {
  215. if (Checked<u32>::addition_would_overflow(offset, (u32)Sizes::OffsetTable)) {
  216. dbgln("Invalid offset in font header");
  217. return nullptr;
  218. }
  219. if (buffer.size() < offset + (u32)Sizes::OffsetTable) {
  220. dbgln("Font file too small");
  221. return nullptr;
  222. }
  223. Optional<ReadonlyBytes> opt_head_slice = {};
  224. Optional<ReadonlyBytes> opt_hhea_slice = {};
  225. Optional<ReadonlyBytes> opt_maxp_slice = {};
  226. Optional<ReadonlyBytes> opt_hmtx_slice = {};
  227. Optional<ReadonlyBytes> opt_cmap_slice = {};
  228. Optional<ReadonlyBytes> opt_loca_slice = {};
  229. Optional<ReadonlyBytes> opt_glyf_slice = {};
  230. Optional<Head> opt_head = {};
  231. Optional<Hhea> opt_hhea = {};
  232. Optional<Maxp> opt_maxp = {};
  233. Optional<Hmtx> opt_hmtx = {};
  234. Optional<Cmap> opt_cmap = {};
  235. Optional<Loca> opt_loca = {};
  236. auto num_tables = be_u16(buffer.offset_pointer(offset + (u32)Offsets::NumTables));
  237. if (buffer.size() < offset + (u32)Sizes::OffsetTable + num_tables * (u32)Sizes::TableRecord) {
  238. dbgln("Font file too small");
  239. return nullptr;
  240. }
  241. for (auto i = 0; i < num_tables; i++) {
  242. u32 record_offset = offset + (u32)Sizes::OffsetTable + i * (u32)Sizes::TableRecord;
  243. u32 tag = be_u32(buffer.offset_pointer(record_offset));
  244. u32 table_offset = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Offset));
  245. u32 table_length = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Length));
  246. if (Checked<u32>::addition_would_overflow(table_offset, table_length)) {
  247. dbgln("Invalid table offset/length in font.");
  248. return nullptr;
  249. }
  250. if (buffer.size() < table_offset + table_length) {
  251. dbgln("Font file too small");
  252. return nullptr;
  253. }
  254. auto buffer_here = ReadonlyBytes(buffer.offset_pointer(table_offset), table_length);
  255. // Get the table offsets we need.
  256. if (tag == tag_from_str("head")) {
  257. opt_head_slice = buffer_here;
  258. } else if (tag == tag_from_str("hhea")) {
  259. opt_hhea_slice = buffer_here;
  260. } else if (tag == tag_from_str("maxp")) {
  261. opt_maxp_slice = buffer_here;
  262. } else if (tag == tag_from_str("hmtx")) {
  263. opt_hmtx_slice = buffer_here;
  264. } else if (tag == tag_from_str("cmap")) {
  265. opt_cmap_slice = buffer_here;
  266. } else if (tag == tag_from_str("loca")) {
  267. opt_loca_slice = buffer_here;
  268. } else if (tag == tag_from_str("glyf")) {
  269. opt_glyf_slice = buffer_here;
  270. }
  271. }
  272. if (!opt_head_slice.has_value() || !(opt_head = Head::from_slice(opt_head_slice.value())).has_value()) {
  273. dbgln("Could not load Head");
  274. return nullptr;
  275. }
  276. auto head = opt_head.value();
  277. if (!opt_hhea_slice.has_value() || !(opt_hhea = Hhea::from_slice(opt_hhea_slice.value())).has_value()) {
  278. dbgln("Could not load Hhea");
  279. return nullptr;
  280. }
  281. auto hhea = opt_hhea.value();
  282. if (!opt_maxp_slice.has_value() || !(opt_maxp = Maxp::from_slice(opt_maxp_slice.value())).has_value()) {
  283. dbgln("Could not load Maxp");
  284. return nullptr;
  285. }
  286. auto maxp = opt_maxp.value();
  287. 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()) {
  288. dbgln("Could not load Hmtx");
  289. return nullptr;
  290. }
  291. auto hmtx = opt_hmtx.value();
  292. if (!opt_cmap_slice.has_value() || !(opt_cmap = Cmap::from_slice(opt_cmap_slice.value())).has_value()) {
  293. dbgln("Could not load Cmap");
  294. return nullptr;
  295. }
  296. auto cmap = opt_cmap.value();
  297. 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()) {
  298. dbgln("Could not load Loca");
  299. return nullptr;
  300. }
  301. auto loca = opt_loca.value();
  302. if (!opt_glyf_slice.has_value()) {
  303. dbgln("Could not load Glyf");
  304. return nullptr;
  305. }
  306. auto glyf = Glyf(opt_glyf_slice.value());
  307. // Select cmap table. FIXME: Do this better. Right now, just looks for platform "Windows"
  308. // and corresponding encoding "Unicode full repertoire", or failing that, "Unicode BMP"
  309. for (u32 i = 0; i < cmap.num_subtables(); i++) {
  310. auto opt_subtable = cmap.subtable(i);
  311. if (!opt_subtable.has_value()) {
  312. continue;
  313. }
  314. auto subtable = opt_subtable.value();
  315. if (subtable.platform_id() == Cmap::Subtable::Platform::Windows) {
  316. if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeFullRepertoire) {
  317. cmap.set_active_index(i);
  318. break;
  319. }
  320. if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeBMP) {
  321. cmap.set_active_index(i);
  322. break;
  323. }
  324. }
  325. }
  326. return adopt(*new Font(move(buffer), move(head), move(hhea), move(maxp), move(hmtx), move(cmap), move(loca), move(glyf)));
  327. }
  328. ScaledFontMetrics Font::metrics(float x_scale, float y_scale) const
  329. {
  330. auto ascender = m_hhea.ascender() * y_scale;
  331. auto descender = m_hhea.descender() * y_scale;
  332. auto line_gap = m_hhea.line_gap() * y_scale;
  333. auto advance_width_max = m_hhea.advance_width_max() * x_scale;
  334. return ScaledFontMetrics {
  335. .ascender = (int)roundf(ascender),
  336. .descender = (int)roundf(descender),
  337. .line_gap = (int)roundf(line_gap),
  338. .advance_width_max = (int)roundf(advance_width_max),
  339. };
  340. }
  341. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  342. ScaledGlyphMetrics Font::glyph_metrics(u32 glyph_id, float x_scale, float y_scale) const
  343. {
  344. if (glyph_id >= glyph_count()) {
  345. glyph_id = 0;
  346. }
  347. auto horizontal_metrics = m_hmtx.get_glyph_horizontal_metrics(glyph_id);
  348. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  349. auto glyph = m_glyf.glyph(glyph_offset);
  350. int ascender = glyph.ascender();
  351. int descender = glyph.descender();
  352. return ScaledGlyphMetrics {
  353. .ascender = (int)roundf(ascender * y_scale),
  354. .descender = (int)roundf(descender * y_scale),
  355. .advance_width = (int)roundf(horizontal_metrics.advance_width * x_scale),
  356. .left_side_bearing = (int)roundf(horizontal_metrics.left_side_bearing * x_scale),
  357. };
  358. }
  359. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  360. RefPtr<Gfx::Bitmap> Font::raster_glyph(u32 glyph_id, float x_scale, float y_scale) const
  361. {
  362. if (glyph_id >= glyph_count()) {
  363. glyph_id = 0;
  364. }
  365. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  366. auto glyph = m_glyf.glyph(glyph_offset);
  367. return glyph.raster(x_scale, y_scale, [&](u16 glyph_id) {
  368. if (glyph_id >= glyph_count()) {
  369. glyph_id = 0;
  370. }
  371. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  372. return m_glyf.glyph(glyph_offset);
  373. });
  374. }
  375. u32 Font::glyph_count() const
  376. {
  377. return m_maxp.num_glyphs();
  378. }
  379. u16 Font::units_per_em() const
  380. {
  381. return m_head.units_per_em();
  382. }
  383. int ScaledFont::width(const StringView& string) const
  384. {
  385. Utf8View utf8 { string };
  386. return width(utf8);
  387. }
  388. int ScaledFont::width(const Utf8View& utf8) const
  389. {
  390. int width = 0;
  391. for (u32 codepoint : utf8) {
  392. u32 glyph_id = glyph_id_for_codepoint(codepoint);
  393. auto metrics = glyph_metrics(glyph_id);
  394. width += metrics.advance_width;
  395. }
  396. return width;
  397. }
  398. int ScaledFont::width(const Utf32View& utf32) const
  399. {
  400. int width = 0;
  401. for (size_t i = 0; i < utf32.length(); i++) {
  402. u32 glyph_id = glyph_id_for_codepoint(utf32.code_points()[i]);
  403. auto metrics = glyph_metrics(glyph_id);
  404. width += metrics.advance_width;
  405. }
  406. return width;
  407. }
  408. RefPtr<Gfx::Bitmap> ScaledFont::raster_glyph(u32 glyph_id) const
  409. {
  410. auto glyph_iterator = m_cached_glyph_bitmaps.find(glyph_id);
  411. if (glyph_iterator != m_cached_glyph_bitmaps.end())
  412. return glyph_iterator->value;
  413. auto glyph_bitmap = m_font->raster_glyph(glyph_id, m_x_scale, m_y_scale);
  414. m_cached_glyph_bitmaps.set(glyph_id, glyph_bitmap);
  415. return glyph_bitmap;
  416. }
  417. }