LineBox.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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/Utf8View.h>
  8. #include <LibWeb/Layout/Box.h>
  9. #include <LibWeb/Layout/LineBox.h>
  10. #include <LibWeb/Layout/Node.h>
  11. #include <LibWeb/Layout/TextNode.h>
  12. namespace Web::Layout {
  13. void LineBox::add_fragment(Node& layout_node, int start, int length, float width, float height, LineBoxFragment::Type fragment_type)
  14. {
  15. bool text_align_is_justify = layout_node.computed_values().text_align() == CSS::TextAlign::Justify;
  16. if (!text_align_is_justify && !m_fragments.is_empty() && &m_fragments.last().layout_node() == &layout_node) {
  17. // The fragment we're adding is from the last Layout::Node on the line.
  18. // Expand the last fragment instead of adding a new one with the same Layout::Node.
  19. m_fragments.last().m_length = (start - m_fragments.last().m_start) + length;
  20. m_fragments.last().set_width(m_fragments.last().width() + width);
  21. } else {
  22. m_fragments.append(make<LineBoxFragment>(layout_node, start, length, Gfx::FloatPoint(m_width, 0.0f), Gfx::FloatSize(width, height), fragment_type));
  23. }
  24. m_width += width;
  25. if (is<Box>(layout_node))
  26. verify_cast<Box>(layout_node).set_containing_line_box_fragment(m_fragments.last());
  27. }
  28. void LineBox::trim_trailing_whitespace()
  29. {
  30. while (!m_fragments.is_empty() && m_fragments.last().is_justifiable_whitespace()) {
  31. auto fragment = m_fragments.take_last();
  32. m_width -= fragment->width();
  33. }
  34. if (m_fragments.is_empty())
  35. return;
  36. auto& last_fragment = m_fragments.last();
  37. auto last_text = last_fragment.text();
  38. if (last_text.is_null())
  39. return;
  40. while (last_fragment.length()) {
  41. auto last_character = last_text[last_fragment.length() - 1];
  42. if (!is_ascii_space(last_character))
  43. break;
  44. int last_character_width = last_fragment.layout_node().font().glyph_width(last_character);
  45. last_fragment.m_length -= 1;
  46. last_fragment.set_width(last_fragment.width() - last_character_width);
  47. m_width -= last_character_width;
  48. }
  49. }
  50. bool LineBox::is_empty_or_ends_in_whitespace() const
  51. {
  52. if (m_fragments.is_empty())
  53. return true;
  54. return m_fragments.last().ends_in_whitespace();
  55. }
  56. }