TextNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibGfx/Painter.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/Layout/BlockBox.h>
  11. #include <LibWeb/Layout/InlineFormattingContext.h>
  12. #include <LibWeb/Layout/Label.h>
  13. #include <LibWeb/Layout/TextNode.h>
  14. #include <LibWeb/Page/Frame.h>
  15. #include <ctype.h>
  16. namespace Web::Layout {
  17. TextNode::TextNode(DOM::Document& document, DOM::Text& text)
  18. : Node(document, &text)
  19. {
  20. set_inline(true);
  21. }
  22. TextNode::~TextNode()
  23. {
  24. }
  25. static bool is_all_whitespace(const StringView& string)
  26. {
  27. for (size_t i = 0; i < string.length(); ++i) {
  28. if (!isspace(string[i]))
  29. return false;
  30. }
  31. return true;
  32. }
  33. void TextNode::paint_fragment(PaintContext& context, const LineBoxFragment& fragment, PaintPhase phase) const
  34. {
  35. auto& painter = context.painter();
  36. if (phase == PaintPhase::Background) {
  37. painter.fill_rect(enclosing_int_rect(fragment.absolute_rect()), computed_values().background_color());
  38. }
  39. if (phase == PaintPhase::Foreground) {
  40. painter.set_font(font());
  41. if (document().inspected_node() == &dom_node())
  42. context.painter().draw_rect(enclosing_int_rect(fragment.absolute_rect()), Color::Magenta);
  43. if (computed_values().text_decoration_line() == CSS::TextDecorationLine::Underline)
  44. painter.draw_line(enclosing_int_rect(fragment.absolute_rect()).bottom_left().translated(0, 1), enclosing_int_rect(fragment.absolute_rect()).bottom_right().translated(0, 1), computed_values().color());
  45. // FIXME: text-transform should be done already in layout, since uppercase glyphs may be wider than lowercase, etc.
  46. auto text = m_text_for_rendering;
  47. auto text_transform = computed_values().text_transform();
  48. if (text_transform == CSS::TextTransform::Uppercase)
  49. text = m_text_for_rendering.to_uppercase();
  50. if (text_transform == CSS::TextTransform::Lowercase)
  51. text = m_text_for_rendering.to_lowercase();
  52. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, computed_values().color());
  53. auto selection_rect = fragment.selection_rect(font());
  54. if (!selection_rect.is_empty()) {
  55. painter.fill_rect(enclosing_int_rect(selection_rect), context.palette().selection());
  56. Gfx::PainterStateSaver saver(painter);
  57. painter.add_clip_rect(enclosing_int_rect(selection_rect));
  58. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, context.palette().selection_text());
  59. }
  60. paint_cursor_if_needed(context, fragment);
  61. }
  62. }
  63. void TextNode::paint_cursor_if_needed(PaintContext& context, const LineBoxFragment& fragment) const
  64. {
  65. if (!frame().is_focused_frame())
  66. return;
  67. if (!frame().cursor_blink_state())
  68. return;
  69. if (frame().cursor_position().node() != &dom_node())
  70. return;
  71. // NOTE: This checks if the cursor is before the start or after the end of the fragment. If it is at the end, after all text, it should still be painted.
  72. if (frame().cursor_position().offset() < (unsigned)fragment.start() || frame().cursor_position().offset() > (unsigned)(fragment.start() + fragment.length()))
  73. return;
  74. if (!fragment.layout_node().dom_node() || !fragment.layout_node().dom_node()->is_editable())
  75. return;
  76. auto fragment_rect = fragment.absolute_rect();
  77. float cursor_x = fragment_rect.x() + font().width(fragment.text().substring_view(0, frame().cursor_position().offset() - fragment.start()));
  78. float cursor_top = fragment_rect.top();
  79. float cursor_height = fragment_rect.height();
  80. Gfx::IntRect cursor_rect(cursor_x, cursor_top, 1, cursor_height);
  81. context.painter().draw_rect(cursor_rect, computed_values().color());
  82. }
  83. void TextNode::compute_text_for_rendering(bool collapse, bool previous_is_empty_or_ends_in_whitespace)
  84. {
  85. if (!collapse) {
  86. m_text_for_rendering = dom_node().data();
  87. return;
  88. }
  89. // Collapse whitespace into single spaces
  90. auto utf8_view = Utf8View(dom_node().data());
  91. StringBuilder builder(dom_node().data().length());
  92. auto it = utf8_view.begin();
  93. auto skip_over_whitespace = [&] {
  94. auto prev = it;
  95. while (it != utf8_view.end() && isspace(*it)) {
  96. prev = it;
  97. ++it;
  98. }
  99. it = prev;
  100. };
  101. if (previous_is_empty_or_ends_in_whitespace)
  102. skip_over_whitespace();
  103. for (; it != utf8_view.end(); ++it) {
  104. if (!isspace(*it)) {
  105. builder.append(utf8_view.as_string().characters_without_null_termination() + utf8_view.byte_offset_of(it), it.code_point_length_in_bytes());
  106. } else {
  107. builder.append(' ');
  108. skip_over_whitespace();
  109. }
  110. }
  111. m_text_for_rendering = builder.to_string();
  112. }
  113. void TextNode::split_into_lines_by_rules(InlineFormattingContext& context, LayoutMode layout_mode, bool do_collapse, bool do_wrap_lines, bool do_wrap_breaks)
  114. {
  115. auto& containing_block = context.containing_block();
  116. auto& font = this->font();
  117. auto& line_boxes = containing_block.line_boxes();
  118. containing_block.ensure_last_line_box();
  119. float available_width = context.available_width_at_line(line_boxes.size() - 1) - line_boxes.last().width();
  120. compute_text_for_rendering(do_collapse, line_boxes.last().is_empty_or_ends_in_whitespace());
  121. ChunkIterator iterator(m_text_for_rendering, layout_mode, do_wrap_lines, do_wrap_breaks);
  122. for (;;) {
  123. auto chunk_opt = iterator.next();
  124. if (!chunk_opt.has_value())
  125. break;
  126. auto& chunk = chunk_opt.value();
  127. // Collapse entire fragment into non-existence if previous fragment on line ended in whitespace.
  128. if (do_collapse && line_boxes.last().is_empty_or_ends_in_whitespace() && chunk.is_all_whitespace)
  129. continue;
  130. float chunk_width;
  131. if (do_wrap_lines) {
  132. if (do_collapse && isspace(*chunk.view.begin()) && line_boxes.last().is_empty_or_ends_in_whitespace()) {
  133. // This is a non-empty chunk that starts with collapsible whitespace.
  134. // We are at either at the start of a new line, or after something that ended in whitespace,
  135. // so we don't need to contribute our own whitespace to the line. Skip over it instead!
  136. ++chunk.start;
  137. --chunk.length;
  138. chunk.view = chunk.view.substring_view(1, chunk.view.byte_length() - 1);
  139. }
  140. chunk_width = font.width(chunk.view) + font.glyph_spacing();
  141. if (line_boxes.last().width() > 0 && chunk_width > available_width) {
  142. containing_block.add_line_box();
  143. available_width = context.available_width_at_line(line_boxes.size() - 1);
  144. if (do_collapse && chunk.is_all_whitespace)
  145. continue;
  146. }
  147. } else {
  148. chunk_width = font.width(chunk.view);
  149. }
  150. line_boxes.last().add_fragment(*this, chunk.start, chunk.length, chunk_width, font.glyph_height());
  151. available_width -= chunk_width;
  152. if (do_wrap_lines && available_width < 0) {
  153. containing_block.add_line_box();
  154. available_width = context.available_width_at_line(line_boxes.size() - 1);
  155. }
  156. if (do_wrap_breaks && chunk.has_breaking_newline) {
  157. containing_block.add_line_box();
  158. available_width = context.available_width_at_line(line_boxes.size() - 1);
  159. }
  160. }
  161. }
  162. void TextNode::split_into_lines(InlineFormattingContext& context, LayoutMode layout_mode)
  163. {
  164. bool do_collapse = true;
  165. bool do_wrap_lines = true;
  166. bool do_wrap_breaks = false;
  167. if (computed_values().white_space() == CSS::WhiteSpace::Nowrap) {
  168. do_collapse = true;
  169. do_wrap_lines = false;
  170. do_wrap_breaks = false;
  171. } else if (computed_values().white_space() == CSS::WhiteSpace::Pre) {
  172. do_collapse = false;
  173. do_wrap_lines = false;
  174. do_wrap_breaks = true;
  175. } else if (computed_values().white_space() == CSS::WhiteSpace::PreLine) {
  176. do_collapse = true;
  177. do_wrap_lines = true;
  178. do_wrap_breaks = true;
  179. } else if (computed_values().white_space() == CSS::WhiteSpace::PreWrap) {
  180. do_collapse = false;
  181. do_wrap_lines = true;
  182. do_wrap_breaks = true;
  183. }
  184. split_into_lines_by_rules(context, layout_mode, do_collapse, do_wrap_lines, do_wrap_breaks);
  185. }
  186. bool TextNode::wants_mouse_events() const
  187. {
  188. return parent() && is<Label>(parent());
  189. }
  190. void TextNode::handle_mousedown(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  191. {
  192. if (!parent() || !is<Label>(*parent()))
  193. return;
  194. downcast<Label>(*parent()).handle_mousedown_on_label({}, position, button);
  195. frame().event_handler().set_mouse_event_tracking_layout_node(this);
  196. }
  197. void TextNode::handle_mouseup(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  198. {
  199. if (!parent() || !is<Label>(*parent()))
  200. return;
  201. // NOTE: Changing the state of the DOM node may run arbitrary JS, which could disappear this node.
  202. NonnullRefPtr protect = *this;
  203. downcast<Label>(*parent()).handle_mouseup_on_label({}, position, button);
  204. frame().event_handler().set_mouse_event_tracking_layout_node(nullptr);
  205. }
  206. void TextNode::handle_mousemove(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  207. {
  208. if (!parent() || !is<Label>(*parent()))
  209. return;
  210. downcast<Label>(*parent()).handle_mousemove_on_label({}, position, button);
  211. }
  212. TextNode::ChunkIterator::ChunkIterator(StringView const& text, LayoutMode layout_mode, bool wrap_lines, bool wrap_breaks)
  213. : m_layout_mode(layout_mode)
  214. , m_wrap_lines(wrap_lines)
  215. , m_wrap_breaks(wrap_breaks)
  216. , m_utf8_view(text)
  217. , m_start_of_chunk(m_utf8_view.begin())
  218. , m_iterator(m_utf8_view.begin())
  219. {
  220. m_last_was_space = !text.is_empty() && isspace(*m_utf8_view.begin());
  221. }
  222. Optional<TextNode::Chunk> TextNode::ChunkIterator::next()
  223. {
  224. while (m_iterator != m_utf8_view.end()) {
  225. auto guard = ScopeGuard([&] { ++m_iterator; });
  226. if (m_layout_mode == LayoutMode::AllPossibleLineBreaks) {
  227. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  228. return result.release_value();
  229. }
  230. if (m_last_was_newline) {
  231. m_last_was_newline = false;
  232. if (auto result = try_commit_chunk(m_iterator, true); result.has_value())
  233. return result.release_value();
  234. }
  235. if (m_wrap_breaks && *m_iterator == '\n') {
  236. m_last_was_newline = true;
  237. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  238. return result.release_value();
  239. }
  240. if (m_wrap_lines) {
  241. bool is_space = isspace(*m_iterator);
  242. if (is_space != m_last_was_space) {
  243. m_last_was_space = is_space;
  244. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  245. return result.release_value();
  246. }
  247. }
  248. }
  249. if (m_last_was_newline) {
  250. m_last_was_newline = false;
  251. if (auto result = try_commit_chunk(m_utf8_view.end(), true); result.has_value())
  252. return result.release_value();
  253. }
  254. if (m_start_of_chunk != m_utf8_view.end()) {
  255. if (auto result = try_commit_chunk(m_utf8_view.end(), false, true); result.has_value())
  256. return result.release_value();
  257. }
  258. return {};
  259. }
  260. Optional<TextNode::Chunk> TextNode::ChunkIterator::try_commit_chunk(Utf8View::Iterator const& it, bool has_breaking_newline, bool must_commit)
  261. {
  262. if (m_layout_mode == LayoutMode::OnlyRequiredLineBreaks && !must_commit)
  263. return {};
  264. auto start = m_utf8_view.byte_offset_of(m_start_of_chunk);
  265. auto length = m_utf8_view.byte_offset_of(it) - m_utf8_view.byte_offset_of(m_start_of_chunk);
  266. if (has_breaking_newline || length > 0) {
  267. auto chunk_view = m_utf8_view.substring_view(start, length);
  268. m_start_of_chunk = it;
  269. return Chunk {
  270. .view = chunk_view,
  271. .start = start,
  272. .length = length,
  273. .has_breaking_newline = has_breaking_newline,
  274. .is_all_whitespace = is_all_whitespace(chunk_view.as_string()),
  275. };
  276. }
  277. m_start_of_chunk = it;
  278. return {};
  279. }
  280. }