LineBox.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Utf8View.h>
  7. #include <LibWeb/Layout/Box.h>
  8. #include <LibWeb/Layout/LineBox.h>
  9. #include <LibWeb/Layout/Node.h>
  10. #include <LibWeb/Layout/TextNode.h>
  11. #include <ctype.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_text = m_fragments.last().text();
  37. if (last_text.is_null())
  38. return;
  39. auto& last_fragment = m_fragments.last();
  40. int space_width = last_fragment.layout_node().font().glyph_width(' ');
  41. while (last_fragment.length() && isspace(last_text[last_fragment.length() - 1])) {
  42. last_fragment.m_length -= 1;
  43. last_fragment.set_width(last_fragment.width() - space_width);
  44. m_width -= space_width;
  45. }
  46. }
  47. bool LineBox::is_empty_or_ends_in_whitespace() const
  48. {
  49. if (m_fragments.is_empty())
  50. return true;
  51. return m_fragments.last().ends_in_whitespace();
  52. }
  53. }