TextLayout.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 <AK/TypeCasts.h>
  9. #include <LibGfx/Font/ScaledFont.h>
  10. #include <harfbuzz/hb.h>
  11. namespace Gfx {
  12. void for_each_glyph_position(FloatPoint baseline_start, Utf8View string, Gfx::Font const& font, Function<void(DrawGlyph const&)> callback, Optional<float&> width)
  13. {
  14. hb_buffer_t* buffer = hb_buffer_create();
  15. ScopeGuard destroy_buffer = [&]() { hb_buffer_destroy(buffer); };
  16. hb_buffer_add_utf8(buffer, reinterpret_cast<char const*>(string.bytes()), string.byte_length(), 0, -1);
  17. hb_buffer_guess_segment_properties(buffer);
  18. u32 glyph_count;
  19. auto* glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
  20. Vector<hb_glyph_info_t> const input_glyph_info({ glyph_info, glyph_count });
  21. if (input_glyph_info.is_empty())
  22. return;
  23. auto* hb_font = font.harfbuzz_font();
  24. hb_shape(hb_font, buffer, nullptr, 0);
  25. glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
  26. auto* positions = hb_buffer_get_glyph_positions(buffer, &glyph_count);
  27. FloatPoint point = baseline_start;
  28. for (size_t i = 0; i < glyph_count; ++i) {
  29. auto position = point
  30. - FloatPoint { 0, font.pixel_metrics().ascent }
  31. + FloatPoint { positions[i].x_offset, positions[i].y_offset } / text_shaping_resolution;
  32. callback(DrawGlyph {
  33. .position = position,
  34. .glyph_id = glyph_info[i].codepoint,
  35. });
  36. point += FloatPoint { positions[i].x_advance, positions[i].y_advance } / text_shaping_resolution;
  37. }
  38. if (width.has_value())
  39. *width = point.x();
  40. }
  41. float measure_text_width(Utf8View const& string, Gfx::Font const& font)
  42. {
  43. float width = 0;
  44. for_each_glyph_position({}, string, font, [&](DrawGlyph const&) {}, width);
  45. return width;
  46. }
  47. }