TextLayout.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "TextLayout.h"
  8. #include "Font/Emoji.h"
  9. #include <AK/TypeCasts.h>
  10. #include <LibGfx/Font/ScaledFont.h>
  11. #include <LibUnicode/Emoji.h>
  12. #include <harfbuzz/hb.h>
  13. namespace Gfx {
  14. static DrawGlyphOrEmoji construct_glyph_or_emoji(size_t index, FloatPoint const& position, Gfx::Font const&, Span<hb_glyph_info_t const> glyph_info, Span<hb_glyph_info_t const>)
  15. {
  16. return DrawGlyph {
  17. .position = position,
  18. .glyph_id = glyph_info[index].codepoint,
  19. };
  20. }
  21. void for_each_glyph_position(FloatPoint baseline_start, Utf8View string, Gfx::Font const& font, Function<void(DrawGlyphOrEmoji const&)> callback, IncludeLeftBearing include_left_bearing, Optional<float&> width)
  22. {
  23. hb_buffer_t* buffer = hb_buffer_create();
  24. ScopeGuard destroy_buffer = [&]() { hb_buffer_destroy(buffer); };
  25. hb_buffer_add_utf8(buffer, reinterpret_cast<char const*>(string.bytes()), string.byte_length(), 0, -1);
  26. hb_buffer_guess_segment_properties(buffer);
  27. u32 glyph_count;
  28. auto* glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
  29. Vector<hb_glyph_info_t> const input_glyph_info({ glyph_info, glyph_count });
  30. if (input_glyph_info.is_empty())
  31. return;
  32. auto* hb_font = font.harfbuzz_font();
  33. hb_shape(hb_font, buffer, nullptr, 0);
  34. glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
  35. auto* positions = hb_buffer_get_glyph_positions(buffer, &glyph_count);
  36. FloatPoint point = baseline_start;
  37. for (size_t i = 0; i < glyph_count; ++i) {
  38. auto position = point
  39. - FloatPoint { 0, font.pixel_metrics().ascent }
  40. + FloatPoint { positions[i].x_offset, positions[i].y_offset } / text_shaping_resolution;
  41. if (include_left_bearing == IncludeLeftBearing::Yes) {
  42. VERIFY(is<Gfx::ScaledFont>(font));
  43. auto bearing = static_cast<Gfx::ScaledFont const&>(font).glyph_metrics(glyph_info[i].codepoint).left_side_bearing;
  44. position += FloatPoint { bearing, 0 };
  45. }
  46. callback(construct_glyph_or_emoji(i, position, font, { glyph_info, glyph_count }, input_glyph_info.span()));
  47. point += FloatPoint { positions[i].x_advance, positions[i].y_advance } / text_shaping_resolution;
  48. }
  49. if (width.has_value())
  50. *width = point.x();
  51. }
  52. }