LineBox.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/TypeCasts.h>
  8. #include <AK/Utf8View.h>
  9. #include <LibWeb/Layout/Box.h>
  10. #include <LibWeb/Layout/BreakNode.h>
  11. #include <LibWeb/Layout/LineBox.h>
  12. #include <LibWeb/Layout/Node.h>
  13. #include <LibWeb/Layout/TextNode.h>
  14. namespace Web::Layout {
  15. void LineBox::add_fragment(Node const& layout_node, int start, int length, float leading_size, float trailing_size, float leading_margin, float trailing_margin, float content_width, float content_height, float border_box_top, float border_box_bottom, LineBoxFragment::Type fragment_type)
  16. {
  17. bool text_align_is_justify = layout_node.computed_values().text_align() == CSS::TextAlign::Justify;
  18. if (!text_align_is_justify && !m_fragments.is_empty() && &m_fragments.last().layout_node() == &layout_node) {
  19. // The fragment we're adding is from the last Layout::Node on the line.
  20. // Expand the last fragment instead of adding a new one with the same Layout::Node.
  21. m_fragments.last().m_length = (start - m_fragments.last().m_start) + length;
  22. m_fragments.last().set_width(m_fragments.last().width() + content_width);
  23. } else {
  24. float x_offset = leading_margin + leading_size + m_width;
  25. float y_offset = 0.0f;
  26. m_fragments.append(LineBoxFragment { layout_node, start, length, Gfx::FloatPoint(x_offset, y_offset), Gfx::FloatSize(content_width, content_height), border_box_top, border_box_bottom, fragment_type });
  27. }
  28. m_width += leading_margin + leading_size + content_width + trailing_size + trailing_margin;
  29. }
  30. void LineBox::trim_trailing_whitespace()
  31. {
  32. while (!m_fragments.is_empty() && m_fragments.last().is_justifiable_whitespace()) {
  33. auto fragment = m_fragments.take_last();
  34. m_width -= fragment.width();
  35. }
  36. if (m_fragments.is_empty())
  37. return;
  38. auto& last_fragment = m_fragments.last();
  39. auto last_text = last_fragment.text();
  40. if (last_text.is_null())
  41. return;
  42. while (last_fragment.length()) {
  43. auto last_character = last_text[last_fragment.length() - 1];
  44. if (!is_ascii_space(last_character))
  45. break;
  46. int last_character_width = last_fragment.layout_node().font().glyph_width(last_character);
  47. last_fragment.m_length -= 1;
  48. last_fragment.set_width(last_fragment.width() - last_character_width);
  49. m_width -= last_character_width;
  50. }
  51. }
  52. bool LineBox::is_empty_or_ends_in_whitespace() const
  53. {
  54. if (m_fragments.is_empty())
  55. return true;
  56. return m_fragments.last().ends_in_whitespace();
  57. }
  58. }