TextLayout.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/Debug.h>
  10. #include <LibUnicode/CharacterTypes.h>
  11. #include <LibUnicode/Emoji.h>
  12. namespace Gfx {
  13. DrawGlyphOrEmoji prepare_draw_glyph_or_emoji(FloatPoint point, Utf8CodePointIterator& it, Font const& font)
  14. {
  15. u32 code_point = *it;
  16. auto next_code_point = it.peek(1);
  17. ScopeGuard consume_variation_selector = [&, initial_it = it] {
  18. // If we advanced the iterator to consume an emoji sequence, don't look for another variation selector.
  19. if (initial_it != it)
  20. return;
  21. // Otherwise, discard one code point if it's a variation selector.
  22. if (next_code_point.has_value() && Unicode::code_point_has_variation_selector_property(*next_code_point))
  23. ++it;
  24. };
  25. // NOTE: We don't check for emoji
  26. auto font_contains_glyph = font.contains_glyph(code_point);
  27. auto check_for_emoji = !font.has_color_bitmaps() && Unicode::could_be_start_of_emoji_sequence(it, font_contains_glyph ? Unicode::SequenceType::EmojiPresentation : Unicode::SequenceType::Any);
  28. // If the font contains the glyph, and we know it's not the start of an emoji, draw a text glyph.
  29. if (font_contains_glyph && !check_for_emoji) {
  30. return DrawGlyph {
  31. .position = point,
  32. .code_point = code_point,
  33. .font = font,
  34. };
  35. }
  36. // If we didn't find a text glyph, or have an emoji variation selector or regional indicator, try to draw an emoji glyph.
  37. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it)) {
  38. return DrawEmoji {
  39. .position = point,
  40. .emoji = emoji,
  41. .font = font,
  42. };
  43. }
  44. // If that failed, but we have a text glyph fallback, draw that.
  45. if (font_contains_glyph) {
  46. return DrawGlyph {
  47. .position = point,
  48. .code_point = code_point,
  49. .font = font,
  50. };
  51. }
  52. // No suitable glyph found, draw a replacement character.
  53. dbgln_if(EMOJI_DEBUG, "Failed to find a glyph or emoji for code_point {}", code_point);
  54. return DrawGlyph {
  55. .position = point,
  56. .code_point = 0xFFFD,
  57. .font = font,
  58. };
  59. }
  60. }