TTFont.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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 "TTFont.h"
  27. #include <AK/FixedArray.h>
  28. #include <AK/LogStream.h>
  29. #include <AK/Utf8View.h>
  30. #include <AK/Utf32View.h>
  31. #include <bits/stdint.h>
  32. #include <LibCore/File.h>
  33. #include <LibGfx/FloatPoint.h>
  34. #include <LibGfx/Path.h>
  35. #include <math.h>
  36. namespace Gfx {
  37. namespace TTF {
  38. static u16 be_u16(const u8* ptr)
  39. {
  40. return (((u16) ptr[0]) << 8) | ((u16) ptr[1]);
  41. }
  42. static u32 be_u32(const u8* ptr)
  43. {
  44. return (((u32) ptr[0]) << 24) | (((u32) ptr[1]) << 16) | (((u32) ptr[2]) << 8) | ((u32) ptr[3]);
  45. }
  46. static i16 be_i16(const u8* ptr)
  47. {
  48. return (((i16) ptr[0]) << 8) | ((i16) ptr[1]);
  49. }
  50. static u32 tag_from_str(const char *str)
  51. {
  52. return be_u32((const u8*) str);
  53. }
  54. u16 Font::Head::units_per_em() const
  55. {
  56. return be_u16(m_slice.offset_pointer((u32) Offsets::UnitsPerEM));
  57. }
  58. i16 Font::Head::xmin() const
  59. {
  60. return be_i16(m_slice.offset_pointer((u32) Offsets::XMin));
  61. }
  62. i16 Font::Head::ymin() const
  63. {
  64. return be_i16(m_slice.offset_pointer((u32) Offsets::YMin));
  65. }
  66. i16 Font::Head::xmax() const
  67. {
  68. return be_i16(m_slice.offset_pointer((u32) Offsets::XMax));
  69. }
  70. i16 Font::Head::ymax() const
  71. {
  72. return be_i16(m_slice.offset_pointer((u32) Offsets::YMax));
  73. }
  74. u16 Font::Head::lowest_recommended_ppem() const
  75. {
  76. return be_u16(m_slice.offset_pointer((u32) Offsets::LowestRecPPEM));
  77. }
  78. Font::IndexToLocFormat Font::Head::index_to_loc_format() const
  79. {
  80. i16 raw = be_i16(m_slice.offset_pointer((u32) Offsets::IndexToLocFormat));
  81. switch (raw) {
  82. case 0:
  83. return IndexToLocFormat::Offset16;
  84. case 1:
  85. return IndexToLocFormat::Offset32;
  86. default:
  87. ASSERT_NOT_REACHED();
  88. }
  89. }
  90. i16 Font::Hhea::ascender() const
  91. {
  92. return be_i16(m_slice.offset_pointer((u32) Offsets::Ascender));
  93. }
  94. i16 Font::Hhea::descender() const
  95. {
  96. return be_i16(m_slice.offset_pointer((u32) Offsets::Descender));
  97. }
  98. i16 Font::Hhea::line_gap() const
  99. {
  100. return be_i16(m_slice.offset_pointer((u32) Offsets::LineGap));
  101. }
  102. u16 Font::Hhea::advance_width_max() const
  103. {
  104. return be_u16(m_slice.offset_pointer((u32) Offsets::AdvanceWidthMax));
  105. }
  106. u16 Font::Hhea::number_of_h_metrics() const
  107. {
  108. return be_u16(m_slice.offset_pointer((u32) Offsets::NumberOfHMetrics));
  109. }
  110. u16 Font::Maxp::num_glyphs() const
  111. {
  112. return be_u16(m_slice.offset_pointer((u32) Offsets::NumGlyphs));
  113. }
  114. enum class SimpleGlyfFlags {
  115. // From spec.
  116. OnCurve = 0x01,
  117. XShortVector = 0x02,
  118. YShortVector = 0x04,
  119. RepeatFlag = 0x08,
  120. XIsSameOrPositiveXShortVector = 0x10,
  121. YIsSameOrPositiveYShortVector = 0x20,
  122. // Combinations
  123. XMask = 0x12,
  124. YMask = 0x24,
  125. XLongVector = 0x00,
  126. YLongVector = 0x00,
  127. XNegativeShortVector = 0x02,
  128. YNegativeShortVector = 0x04,
  129. XPositiveShortVector = 0x12,
  130. YPositiveShortVector = 0x24,
  131. };
  132. class PointIterator {
  133. public:
  134. struct Item {
  135. bool on_curve;
  136. FloatPoint point;
  137. };
  138. PointIterator(const ByteBuffer& slice, u16 num_points, u32 flags_offset, u32 x_offset, u32 y_offset, float x_translate, float y_translate, float x_scale, float y_scale)
  139. : m_slice(slice)
  140. , m_points_remaining(num_points)
  141. , m_flags_offset(flags_offset)
  142. , m_x_offset(x_offset)
  143. , m_y_offset(y_offset)
  144. , m_x_translate(x_translate)
  145. , m_y_translate(y_translate)
  146. , m_x_scale(x_scale)
  147. , m_y_scale(y_scale)
  148. {
  149. }
  150. Optional<Item> next()
  151. {
  152. if (m_points_remaining == 0) {
  153. return {};
  154. }
  155. if (m_flags_remaining > 0) {
  156. m_flags_remaining--;
  157. } else {
  158. m_flag = m_slice[m_flags_offset++];
  159. if (m_flag & (u8) SimpleGlyfFlags::RepeatFlag) {
  160. m_flags_remaining = m_slice[m_flags_offset++];
  161. }
  162. }
  163. switch (m_flag & (u8) SimpleGlyfFlags::XMask) {
  164. case (u8) SimpleGlyfFlags::XLongVector:
  165. m_last_point.set_x(m_last_point.x() + be_i16(m_slice.offset_pointer(m_x_offset)));
  166. m_x_offset += 2;
  167. break;
  168. case (u8) SimpleGlyfFlags::XNegativeShortVector:
  169. m_last_point.set_x(m_last_point.x() - m_slice[m_x_offset++]);
  170. break;
  171. case (u8) SimpleGlyfFlags::XPositiveShortVector:
  172. m_last_point.set_x(m_last_point.x() + m_slice[m_x_offset++]);
  173. break;
  174. default:
  175. break;
  176. }
  177. switch (m_flag & (u8) SimpleGlyfFlags::YMask) {
  178. case (u8) SimpleGlyfFlags::YLongVector:
  179. m_last_point.set_y(m_last_point.y() + be_i16(m_slice.offset_pointer(m_y_offset)));
  180. m_y_offset += 2;
  181. break;
  182. case (u8) SimpleGlyfFlags::YNegativeShortVector:
  183. m_last_point.set_y(m_last_point.y() - m_slice[m_y_offset++]);
  184. break;
  185. case (u8) SimpleGlyfFlags::YPositiveShortVector:
  186. m_last_point.set_y(m_last_point.y() + m_slice[m_y_offset++]);
  187. break;
  188. default:
  189. break;
  190. }
  191. m_points_remaining--;
  192. Item ret = {
  193. .on_curve = (m_flag & (u8) SimpleGlyfFlags::OnCurve) != 0,
  194. .point = m_last_point,
  195. };
  196. ret.point.move_by(m_x_translate, m_y_translate);
  197. ret.point.set_x(ret.point.x() * m_x_scale);
  198. ret.point.set_y(ret.point.y() * m_y_scale);
  199. return ret;
  200. }
  201. private:
  202. ByteBuffer m_slice;
  203. u16 m_points_remaining;
  204. u8 m_flag { 0 };
  205. FloatPoint m_last_point = { 0.0f, 0.0f };
  206. u32 m_flags_remaining = { 0 };
  207. u32 m_flags_offset;
  208. u32 m_x_offset;
  209. u32 m_y_offset;
  210. float m_x_translate;
  211. float m_y_translate;
  212. float m_x_scale;
  213. float m_y_scale;
  214. };
  215. class Rasterizer {
  216. public:
  217. Rasterizer(Size size)
  218. : m_size(size)
  219. , m_data(m_size.width() * m_size.height())
  220. {
  221. for (int i = 0; i < m_size.width() * m_size.height(); i++) {
  222. m_data[i] = 0.0;
  223. }
  224. }
  225. RefPtr<Bitmap> draw_path(Path& path)
  226. {
  227. for (auto& line : path.split_lines()) {
  228. draw_line(line.from, line.to);
  229. }
  230. return accumulate();
  231. }
  232. private:
  233. RefPtr<Bitmap> accumulate()
  234. {
  235. auto bitmap = Bitmap::create(BitmapFormat::RGBA32, m_size);
  236. Color base_color = Color::from_rgb(0xffffff);
  237. for (int y = 0; y < m_size.height(); y++) {
  238. float accumulator = 0.0;
  239. for (int x = 0; x < m_size.width(); x++) {
  240. accumulator += m_data[y * m_size.width() + x];
  241. float value = accumulator;
  242. if (value < 0.0) {
  243. value = -value;
  244. }
  245. if (value > 1.0) {
  246. value = 1.0;
  247. }
  248. u8 alpha = value * 255.0;
  249. bitmap->set_pixel(x, y, base_color.with_alpha(alpha));
  250. }
  251. }
  252. return bitmap;
  253. }
  254. void draw_line(FloatPoint p0, FloatPoint p1)
  255. {
  256. ASSERT(p0.x() >= 0.0 && p0.y() >= 0.0 && p0.x() <= m_size.width() && p0.y() <= m_size.height());
  257. ASSERT(p1.x() >= 0.0 && p1.y() >= 0.0 && p1.x() <= m_size.width() && p1.y() <= m_size.height());
  258. // If we're on the same Y, there's no need to draw
  259. if (p0.y() == p1.y()) {
  260. return;
  261. }
  262. float direction = -1.0;
  263. if (p1.y() < p0.y()) {
  264. direction = 1.0;
  265. auto tmp = p0;
  266. p0 = p1;
  267. p1 = tmp;
  268. }
  269. float dxdy = (p1.x() - p0.x()) / (p1.y() - p0.y());
  270. u32 y0 = floor(p0.y());
  271. u32 y1 = ceil(p1.y());
  272. float x_cur = p0.x();
  273. for (u32 y = y0; y < y1; y++) {
  274. u32 line_offset = m_size.width() * y;
  275. float dy = min(y + 1.0f, p1.y()) - max((float) y, p0.y());
  276. float directed_dy = dy * direction;
  277. float x_next = x_cur + dy * dxdy;
  278. if (x_next < 0.0) {
  279. x_next = 0.0;
  280. }
  281. float x0 = x_cur;
  282. float x1 = x_next;
  283. if (x1 < x0) {
  284. x1 = x_cur;
  285. x0 = x_next;
  286. }
  287. float x0_floor = floor(x0);
  288. float x1_ceil = ceil(x1);
  289. u32 x0i = x0_floor;
  290. if (x1_ceil <= x0_floor + 1.0) {
  291. // If x0 and x1 are within the same pixel, then area to the right is (1 - (mid(x0, x1) - x0_floor)) * dy
  292. float area = ((x0 + x1) * 0.5) - x0_floor;
  293. m_data[line_offset + x0i] += directed_dy * (1.0 - area);
  294. m_data[line_offset + x0i + 1] += directed_dy * area;
  295. } else {
  296. float dydx = 1.0 / dxdy;
  297. float x0_right = 1.0 - (x0 - x0_floor);
  298. u32 x1_floor_i = floor(x1);
  299. float area_upto_here = 0.5 * x0_right * x0_right * dydx;
  300. m_data[line_offset + x0i] += direction * area_upto_here;
  301. for (u32 x = x0i + 1; x < x1_floor_i; x++) {
  302. x0_right += 1.0;
  303. float total_area_here = 0.5 * x0_right * x0_right * dydx;
  304. m_data[line_offset + x] += direction * (total_area_here - area_upto_here);
  305. area_upto_here = total_area_here;
  306. }
  307. m_data[line_offset + x1_floor_i] += direction * (dy - area_upto_here);
  308. }
  309. x_cur = x_next;
  310. }
  311. }
  312. Size m_size;
  313. FixedArray<float> m_data;
  314. };
  315. Font::GlyphHorizontalMetrics Font::Hmtx::get_glyph_horizontal_metrics(u32 glyph_id) const
  316. {
  317. ASSERT(glyph_id < m_num_glyphs);
  318. if (glyph_id < m_number_of_h_metrics) {
  319. auto offset = glyph_id * (u32) Sizes::LongHorMetric;
  320. u16 advance_width = be_u16(m_slice.offset_pointer(offset));
  321. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset + 2));
  322. return GlyphHorizontalMetrics {
  323. .advance_width = advance_width,
  324. .left_side_bearing = left_side_bearing,
  325. };
  326. }
  327. auto offset = m_number_of_h_metrics * (u32) Sizes::LongHorMetric + (glyph_id - m_number_of_h_metrics) * (u32) Sizes::LeftSideBearing;
  328. u16 advance_width = be_u16(m_slice.offset_pointer((m_number_of_h_metrics - 1) * (u32) Sizes::LongHorMetric));
  329. i16 left_side_bearing = be_i16(m_slice.offset_pointer(offset));
  330. return GlyphHorizontalMetrics {
  331. .advance_width = advance_width,
  332. .left_side_bearing = left_side_bearing,
  333. };
  334. }
  335. Font::Cmap::Subtable::Platform Font::Cmap::Subtable::platform_id() const
  336. {
  337. switch (m_raw_platform_id) {
  338. case 0: return Platform::Unicode;
  339. case 1: return Platform::Macintosh;
  340. case 3: return Platform::Windows;
  341. case 4: return Platform::Custom;
  342. default: ASSERT_NOT_REACHED();
  343. }
  344. }
  345. Font::Cmap::Subtable::Format Font::Cmap::Subtable::format() const
  346. {
  347. switch (be_u16(m_slice.offset_pointer(0))) {
  348. case 0: return Format::ByteEncoding;
  349. case 2: return Format::HighByte;
  350. case 4: return Format::SegmentToDelta;
  351. case 6: return Format::TrimmedTable;
  352. case 8: return Format::Mixed16And32;
  353. case 10: return Format::TrimmedArray;
  354. case 12: return Format::SegmentedCoverage;
  355. case 13: return Format::ManyToOneRange;
  356. case 14: return Format::UnicodeVariationSequences;
  357. default: ASSERT_NOT_REACHED();
  358. }
  359. }
  360. u32 Font::Cmap::num_subtables() const
  361. {
  362. return be_u16(m_slice.offset_pointer((u32) Offsets::NumTables));
  363. }
  364. Optional<Font::Cmap::Subtable> Font::Cmap::subtable(u32 index) const
  365. {
  366. if (index >= num_subtables()) {
  367. return {};
  368. }
  369. u32 record_offset = (u32) Sizes::TableHeader + index * (u32) Sizes::EncodingRecord;
  370. u16 platform_id = be_u16(m_slice.offset_pointer(record_offset));
  371. u16 encoding_id = be_u16(m_slice.offset_pointer(record_offset + (u32) Offsets::EncodingRecord_EncodingID));
  372. u32 subtable_offset = be_u32(m_slice.offset_pointer(record_offset + (u32) Offsets::EncodingRecord_Offset));
  373. ASSERT(subtable_offset < m_slice.size());
  374. auto subtable_slice = ByteBuffer::wrap(m_slice.offset_pointer(subtable_offset), m_slice.size() - subtable_offset);
  375. return Subtable(subtable_slice, platform_id, encoding_id);
  376. }
  377. // FIXME: This only handles formats 4 (SegmentToDelta) and 12 (SegmentedCoverage) for now.
  378. u32 Font::Cmap::Subtable::glyph_id_for_codepoint(u32 codepoint) const
  379. {
  380. switch (format()) {
  381. case Format::SegmentToDelta:
  382. return glyph_id_for_codepoint_table_4(codepoint);
  383. case Format::SegmentedCoverage:
  384. return glyph_id_for_codepoint_table_12(codepoint);
  385. default:
  386. return 0;
  387. }
  388. }
  389. u32 Font::Cmap::Subtable::glyph_id_for_codepoint_table_4(u32 codepoint) const
  390. {
  391. u32 segcount_x2 = be_u16(m_slice.offset_pointer((u32) Table4Offsets::SegCountX2));
  392. if (m_slice.size() < segcount_x2 * (u32) Table4Sizes::NonConstMultiplier + (u32) Table4Sizes::Constant) {
  393. return 0;
  394. }
  395. for (u32 offset = 0; offset < segcount_x2; offset += 2) {
  396. u32 end_codepoint = be_u16(m_slice.offset_pointer((u32) Table4Offsets::EndConstBase + offset));
  397. if (codepoint > end_codepoint) {
  398. continue;
  399. }
  400. u32 start_codepoint = be_u16(m_slice.offset_pointer((u32) Table4Offsets::StartConstBase + segcount_x2 + offset));
  401. if (codepoint < start_codepoint) {
  402. break;
  403. }
  404. u32 delta = be_u16(m_slice.offset_pointer((u32) Table4Offsets::DeltaConstBase + segcount_x2 * 2 + offset));
  405. u32 range = be_u16(m_slice.offset_pointer((u32) Table4Offsets::RangeConstBase + segcount_x2 * 3 + offset));
  406. if (range == 0) {
  407. return (codepoint + delta) & 0xffff;
  408. }
  409. u32 glyph_offset = (u32) Table4Offsets::GlyphOffsetConstBase + segcount_x2 * 3 + offset + range + (codepoint - start_codepoint) * 2;
  410. ASSERT(glyph_offset + 2 <= m_slice.size());
  411. return (be_u16(m_slice.offset_pointer(glyph_offset)) + delta) & 0xffff;
  412. }
  413. return 0;
  414. }
  415. u32 Font::Cmap::Subtable::glyph_id_for_codepoint_table_12(u32 codepoint) const
  416. {
  417. u32 num_groups = be_u32(m_slice.offset_pointer((u32) Table12Offsets::NumGroups));
  418. ASSERT(m_slice.size() >= (u32) Table12Sizes::Header + (u32) Table12Sizes::Record * num_groups);
  419. for (u32 offset = 0; offset < num_groups * (u32) Table12Sizes::Record; offset += (u32) Table12Sizes::Record) {
  420. u32 start_codepoint = be_u32(m_slice.offset_pointer((u32) Table12Offsets::Record_StartCode + offset));
  421. if (codepoint < start_codepoint) {
  422. break;
  423. }
  424. u32 end_codepoint = be_u32(m_slice.offset_pointer((u32) Table12Offsets::Record_EndCode + offset));
  425. if (codepoint > end_codepoint) {
  426. continue;
  427. }
  428. u32 glyph_offset = be_u32(m_slice.offset_pointer((u32) Table12Offsets::Record_StartGlyph + offset));
  429. return codepoint - start_codepoint + glyph_offset;
  430. }
  431. return 0;
  432. }
  433. u32 Font::Cmap::glyph_id_for_codepoint(u32 codepoint) const
  434. {
  435. auto opt_subtable = subtable(m_active_index);
  436. if (!opt_subtable.has_value()) {
  437. return 0;
  438. }
  439. auto subtable = opt_subtable.value();
  440. return subtable.glyph_id_for_codepoint(codepoint);
  441. }
  442. u32 Font::Loca::get_glyph_offset(u32 glyph_id) const
  443. {
  444. ASSERT(glyph_id < m_num_glyphs);
  445. switch (m_index_to_loc_format) {
  446. case IndexToLocFormat::Offset16:
  447. return ((u32) be_u16(m_slice.offset_pointer(glyph_id * 2))) * 2;
  448. case IndexToLocFormat::Offset32:
  449. return be_u32(m_slice.offset_pointer(glyph_id * 4));
  450. default:
  451. ASSERT_NOT_REACHED();
  452. }
  453. }
  454. Font::Glyf::Glyph Font::Glyf::Glyph::simple(const ByteBuffer& slice, u16 num_contours, i16 xmin, i16 ymin, i16 xmax, i16 ymax)
  455. {
  456. auto ret = Glyph(slice, Type::Simple);
  457. ret.m_meta.simple = Simple {
  458. .num_contours = num_contours,
  459. .xmin = xmin,
  460. .ymin = ymin,
  461. .xmax = xmax,
  462. .ymax = ymax,
  463. };
  464. return ret;
  465. }
  466. // FIXME: This is currently just a dummy. Need to add support for composite glyphs.
  467. Font::Glyf::Glyph Font::Glyf::Glyph::composite(const ByteBuffer& slice)
  468. {
  469. auto ret = Glyph(slice, Type::Composite);
  470. ret.m_meta.composite = Composite();
  471. return ret;
  472. }
  473. RefPtr<Bitmap> Font::Glyf::Glyph::raster(float x_scale, float y_scale) const
  474. {
  475. switch (m_type) {
  476. case Type::Simple:
  477. return raster_simple(x_scale, y_scale);
  478. case Type::Composite:
  479. // FIXME: Add support for composite glyphs
  480. TODO();
  481. }
  482. ASSERT_NOT_REACHED();
  483. }
  484. static void get_ttglyph_offsets(const ByteBuffer& slice, u32 num_points, u32 flags_offset, u32 *x_offset, u32 *y_offset)
  485. {
  486. u32 flags_size = 0;
  487. u32 x_size = 0;
  488. u32 repeat_count;
  489. while (num_points > 0) {
  490. u8 flag = slice[flags_offset + flags_size];
  491. if (flag & (u8) SimpleGlyfFlags::RepeatFlag) {
  492. flags_size++;
  493. repeat_count = slice[flags_offset + flags_size] + 1;
  494. } else {
  495. repeat_count = 1;
  496. }
  497. flags_size++;
  498. switch (flag & (u8) SimpleGlyfFlags::XMask) {
  499. case (u8) SimpleGlyfFlags::XLongVector:
  500. x_size += repeat_count * 2;
  501. break;
  502. case (u8) SimpleGlyfFlags::XNegativeShortVector:
  503. case (u8) SimpleGlyfFlags::XPositiveShortVector:
  504. x_size += repeat_count;
  505. break;
  506. default:
  507. break;
  508. }
  509. num_points -= repeat_count;
  510. }
  511. *x_offset = flags_offset + flags_size;
  512. *y_offset = *x_offset + x_size;
  513. }
  514. RefPtr<Bitmap> Font::Glyf::Glyph::raster_simple(float x_scale, float y_scale) const
  515. {
  516. auto simple = m_meta.simple;
  517. // Get offets for flags, x, and y.
  518. u16 num_points = be_u16(m_slice.offset_pointer((simple.num_contours - 1) * 2)) + 1;
  519. u16 num_instructions = be_u16(m_slice.offset_pointer(simple.num_contours * 2));
  520. u32 flags_offset = simple.num_contours * 2 + 2 + num_instructions;
  521. u32 x_offset = 0;
  522. u32 y_offset = 0;
  523. get_ttglyph_offsets(m_slice, num_points, flags_offset, &x_offset, &y_offset);
  524. // Prepare to render glyph.
  525. u32 width = (u32) (ceil((simple.xmax - simple.xmin) * x_scale)) + 1;
  526. u32 height = (u32) (ceil((simple.ymax - simple.ymin) * y_scale)) + 1;
  527. Path path;
  528. PointIterator point_iterator(m_slice, num_points, flags_offset, x_offset, y_offset, -simple.xmin, -simple.ymax, x_scale, -y_scale);
  529. int last_contour_end = -1;
  530. u32 contour_index = 0;
  531. u32 contour_size = 0;
  532. Optional<FloatPoint> contour_start = {};
  533. Optional<FloatPoint> last_offcurve_point = {};
  534. // Render glyph
  535. while (true) {
  536. if (!contour_start.has_value()) {
  537. if (contour_index >= simple.num_contours) {
  538. break;
  539. }
  540. int current_contour_end = be_u16(m_slice.offset_pointer(contour_index++ * 2));
  541. contour_size = current_contour_end - last_contour_end;
  542. last_contour_end = current_contour_end;
  543. auto opt_item = point_iterator.next();
  544. if (!opt_item.has_value()) {
  545. ASSERT_NOT_REACHED();
  546. }
  547. contour_start = opt_item.value().point;
  548. path.move_to(contour_start.value());
  549. contour_size--;
  550. } else if (!last_offcurve_point.has_value()) {
  551. if (contour_size > 0) {
  552. auto opt_item = point_iterator.next();
  553. // FIXME: Should we draw a line to the first point here?
  554. if (!opt_item.has_value()) {
  555. break;
  556. }
  557. auto item = opt_item.value();
  558. contour_size--;
  559. if (item.on_curve) {
  560. path.line_to(item.point);
  561. } else if (contour_size > 0) {
  562. auto opt_next_item = point_iterator.next();
  563. // FIXME: Should we draw a quadratic bezier to the first point here?
  564. if (!opt_next_item.has_value()) {
  565. break;
  566. }
  567. auto next_item = opt_next_item.value();
  568. contour_size--;
  569. if (next_item.on_curve) {
  570. path.quadratic_bezier_curve_to(item.point, next_item.point);
  571. } else {
  572. auto mid_point = FloatPoint::interpolate(item.point, next_item.point, 0.5);
  573. path.quadratic_bezier_curve_to(item.point, mid_point);
  574. last_offcurve_point = next_item.point;
  575. }
  576. } else {
  577. path.quadratic_bezier_curve_to(item.point, contour_start.value());
  578. contour_start = {};
  579. }
  580. } else {
  581. path.line_to(contour_start.value());
  582. contour_start = {};
  583. }
  584. } else {
  585. auto point0 = last_offcurve_point.value();
  586. last_offcurve_point = {};
  587. if (contour_size > 0) {
  588. auto opt_item = point_iterator.next();
  589. // FIXME: Should we draw a quadratic bezier to the first point here?
  590. if (!opt_item.has_value()) {
  591. break;
  592. }
  593. auto item = opt_item.value();
  594. contour_size--;
  595. if (item.on_curve) {
  596. path.quadratic_bezier_curve_to(point0, item.point);
  597. } else {
  598. auto mid_point = FloatPoint::interpolate(point0, item.point, 0.5);
  599. path.quadratic_bezier_curve_to(point0, mid_point);
  600. last_offcurve_point = item.point;
  601. }
  602. } else {
  603. path.quadratic_bezier_curve_to(point0, contour_start.value());
  604. contour_start = {};
  605. }
  606. }
  607. }
  608. return Rasterizer(Size(width, height)).draw_path(path);
  609. }
  610. Font::Glyf::Glyph Font::Glyf::glyph(u32 offset) const
  611. {
  612. ASSERT(m_slice.size() >= offset + (u32) Sizes::GlyphHeader);
  613. i16 num_contours = be_i16(m_slice.offset_pointer(offset));
  614. i16 xmin = be_i16(m_slice.offset_pointer(offset + (u32) Offsets::XMin));
  615. i16 ymin = be_i16(m_slice.offset_pointer(offset + (u32) Offsets::YMin));
  616. i16 xmax = be_i16(m_slice.offset_pointer(offset + (u32) Offsets::XMax));
  617. i16 ymax = be_i16(m_slice.offset_pointer(offset + (u32) Offsets::YMax));
  618. auto slice = ByteBuffer::wrap(m_slice.offset_pointer(offset + (u32) Sizes::GlyphHeader), m_slice.size() - offset - (u32) Sizes::GlyphHeader);
  619. if (num_contours < 0) {
  620. return Glyph::composite(slice);
  621. }
  622. return Glyph::simple(slice, num_contours, xmin, ymin, xmax, ymax);
  623. }
  624. RefPtr<Font> Font::load_from_file(const StringView& path, unsigned index)
  625. {
  626. auto file_or_error = Core::File::open(String(path), Core::IODevice::ReadOnly);
  627. if (file_or_error.is_error()) {
  628. dbg() << "Could not open file: " << file_or_error.error();
  629. return nullptr;
  630. }
  631. auto file = file_or_error.value();
  632. if (!file->open(Core::IODevice::ReadOnly)) {
  633. dbg() << "Could not open file";
  634. return nullptr;
  635. }
  636. auto buffer = file->read_all();
  637. if (buffer.size() < 4) {
  638. dbg() << "Font file too small";
  639. return nullptr;
  640. }
  641. u32 tag = be_u32(buffer.data());
  642. if (tag == tag_from_str("ttcf")) {
  643. // It's a font collection
  644. if (buffer.size() < (u32) Sizes::TTCHeaderV1 + sizeof(u32) * (index + 1)) {
  645. dbg() << "Font file too small";
  646. return nullptr;
  647. }
  648. u32 offset = be_u32(buffer.offset_pointer((u32) Sizes::TTCHeaderV1 + sizeof(u32) * index));
  649. return adopt(*new Font(move(buffer), offset));
  650. }
  651. if (tag == tag_from_str("OTTO")) {
  652. dbg() << "CFF fonts not supported yet";
  653. return nullptr;
  654. }
  655. if (tag != 0x00010000) {
  656. dbg() << "Not a valid font";
  657. return nullptr;
  658. }
  659. return adopt(*new Font(move(buffer), 0));
  660. }
  661. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  662. Font::Font(ByteBuffer&& buffer, u32 offset)
  663. : m_buffer(move(buffer))
  664. {
  665. ASSERT(m_buffer.size() >= offset + (u32) Sizes::OffsetTable);
  666. Optional<ByteBuffer> head_slice = {};
  667. Optional<ByteBuffer> hhea_slice = {};
  668. Optional<ByteBuffer> maxp_slice = {};
  669. Optional<ByteBuffer> hmtx_slice = {};
  670. Optional<ByteBuffer> cmap_slice = {};
  671. Optional<ByteBuffer> loca_slice = {};
  672. Optional<ByteBuffer> glyf_slice = {};
  673. //auto sfnt_version = be_u32(data + offset);
  674. auto num_tables = be_u16(m_buffer.offset_pointer(offset + (u32) Offsets::NumTables));
  675. ASSERT(m_buffer.size() >= offset + (u32) Sizes::OffsetTable + num_tables * (u32) Sizes::TableRecord);
  676. for (auto i = 0; i < num_tables; i++) {
  677. u32 record_offset = offset + (u32) Sizes::OffsetTable + i * (u32) Sizes::TableRecord;
  678. u32 tag = be_u32(m_buffer.offset_pointer(record_offset));
  679. u32 table_offset = be_u32(m_buffer.offset_pointer(record_offset + (u32) Offsets::TableRecord_Offset));
  680. u32 table_length = be_u32(m_buffer.offset_pointer(record_offset + (u32) Offsets::TableRecord_Length));
  681. ASSERT(m_buffer.size() >= table_offset + table_length);
  682. auto buffer = ByteBuffer::wrap(m_buffer.offset_pointer(table_offset), table_length);
  683. // Get the table offsets we need.
  684. if (tag == tag_from_str("head")) {
  685. head_slice = buffer;
  686. } else if (tag == tag_from_str("hhea")) {
  687. hhea_slice = buffer;
  688. } else if (tag == tag_from_str("maxp")) {
  689. maxp_slice = buffer;
  690. } else if (tag == tag_from_str("hmtx")) {
  691. hmtx_slice = buffer;
  692. } else if (tag == tag_from_str("cmap")) {
  693. cmap_slice = buffer;
  694. } else if (tag == tag_from_str("loca")) {
  695. loca_slice = buffer;
  696. } else if (tag == tag_from_str("glyf")) {
  697. glyf_slice = buffer;
  698. }
  699. }
  700. // Check that we've got everything we need.
  701. ASSERT(head_slice.has_value());
  702. ASSERT(hhea_slice.has_value());
  703. ASSERT(maxp_slice.has_value());
  704. ASSERT(hmtx_slice.has_value());
  705. ASSERT(cmap_slice.has_value());
  706. ASSERT(loca_slice.has_value());
  707. ASSERT(glyf_slice.has_value());
  708. // Load the tables.
  709. m_head = Head(head_slice.value());
  710. m_hhea = Hhea(hhea_slice.value());
  711. m_maxp = Maxp(maxp_slice.value());
  712. m_hmtx = Hmtx(hmtx_slice.value(), m_maxp.num_glyphs(), m_hhea.number_of_h_metrics());
  713. m_cmap = Cmap(cmap_slice.value());
  714. m_loca = Loca(loca_slice.value(), m_maxp.num_glyphs(), m_head.index_to_loc_format());
  715. m_glyf = Glyf(glyf_slice.value());
  716. // Select cmap table. FIXME: Do this better. Right now, just looks for platform "Windows"
  717. // and corresponding encoding "Unicode full repertoire", or failing that, "Unicode BMP"
  718. for (u32 i = 0; i < m_cmap.num_subtables(); i++) {
  719. auto opt_subtable = m_cmap.subtable(i);
  720. if (!opt_subtable.has_value()) {
  721. continue;
  722. }
  723. auto subtable = opt_subtable.value();
  724. if (subtable.platform_id() == Cmap::Subtable::Platform::Windows) {
  725. if (subtable.encoding_id() == (u16) Cmap::Subtable::WindowsEncoding::UnicodeFullRepertoire) {
  726. m_cmap.set_active_index(i);
  727. break;
  728. }
  729. if (subtable.encoding_id() == (u16) Cmap::Subtable::WindowsEncoding::UnicodeBMP) {
  730. m_cmap.set_active_index(i);
  731. break;
  732. }
  733. }
  734. }
  735. }
  736. ScaledFontMetrics Font::metrics(float x_scale, float y_scale) const
  737. {
  738. auto ascender = m_hhea.ascender() * y_scale;
  739. auto descender = m_hhea.descender() * y_scale;
  740. auto line_gap = m_hhea.line_gap() * y_scale;
  741. auto advance_width_max = m_hhea.advance_width_max() * x_scale;
  742. return ScaledFontMetrics {
  743. .ascender = (int) roundf(ascender),
  744. .descender = (int) roundf(descender),
  745. .line_gap = (int) roundf(line_gap),
  746. .advance_width_max = (int) roundf(advance_width_max),
  747. };
  748. }
  749. ScaledGlyphMetrics Font::glyph_metrics(u32 glyph_id, float x_scale, float y_scale) const
  750. {
  751. if (glyph_id >= m_maxp.num_glyphs()) {
  752. glyph_id = 0;
  753. }
  754. auto horizontal_metrics = m_hmtx.get_glyph_horizontal_metrics(glyph_id);
  755. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  756. auto glyph = m_glyf.glyph(glyph_offset);
  757. int ascender = glyph.ascender();
  758. int descender = glyph.descender();
  759. return ScaledGlyphMetrics {
  760. .ascender = (int) roundf(ascender * y_scale),
  761. .descender = (int) roundf(descender * y_scale),
  762. .advance_width = (int) roundf(horizontal_metrics.advance_width * x_scale),
  763. .left_side_bearing = (int) roundf(horizontal_metrics.left_side_bearing * x_scale),
  764. };
  765. }
  766. // FIXME: "loca" and "glyf" are not available for CFF fonts.
  767. RefPtr<Bitmap> Font::raster_glyph(u32 glyph_id, float x_scale, float y_scale) const
  768. {
  769. if (glyph_id >= m_maxp.num_glyphs()) {
  770. glyph_id = 0;
  771. }
  772. auto glyph_offset = m_loca.get_glyph_offset(glyph_id);
  773. auto glyph = m_glyf.glyph(glyph_offset);
  774. return glyph.raster(x_scale, y_scale);
  775. }
  776. int ScaledFont::width(const StringView& string) const
  777. {
  778. Utf8View utf8 { string };
  779. return width(utf8);
  780. }
  781. int ScaledFont::width(const Utf8View& utf8) const
  782. {
  783. int width = 0;
  784. for (u32 codepoint : utf8) {
  785. u32 glyph_id = glyph_id_for_codepoint(codepoint);
  786. auto metrics = glyph_metrics(glyph_id);
  787. width += metrics.advance_width;
  788. }
  789. return width;
  790. }
  791. int ScaledFont::width(const Utf32View& utf32) const
  792. {
  793. int width = 0;
  794. for (size_t i = 0; i < utf32.length(); i++) {
  795. u32 glyph_id = glyph_id_for_codepoint(utf32.codepoints()[i]);
  796. auto metrics = glyph_metrics(glyph_id);
  797. width += metrics.advance_width;
  798. }
  799. return width;
  800. }
  801. }
  802. }