TextNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. if (!(frame().cursor_position().offset() >= (unsigned)fragment.start() && frame().cursor_position().offset() < (unsigned)(fragment.start() + fragment.length())))
  72. return;
  73. if (!fragment.layout_node().dom_node() || !fragment.layout_node().dom_node()->is_editable())
  74. return;
  75. auto fragment_rect = fragment.absolute_rect();
  76. float cursor_x = fragment_rect.x() + font().width(fragment.text().substring_view(0, frame().cursor_position().offset() - fragment.start()));
  77. float cursor_top = fragment_rect.top();
  78. float cursor_height = fragment_rect.height();
  79. Gfx::IntRect cursor_rect(cursor_x, cursor_top, 1, cursor_height);
  80. context.painter().draw_rect(cursor_rect, computed_values().color());
  81. }
  82. void TextNode::compute_text_for_rendering(bool collapse, bool previous_is_empty_or_ends_in_whitespace)
  83. {
  84. if (!collapse) {
  85. m_text_for_rendering = dom_node().data();
  86. return;
  87. }
  88. // Collapse whitespace into single spaces
  89. auto utf8_view = Utf8View(dom_node().data());
  90. StringBuilder builder(dom_node().data().length());
  91. auto it = utf8_view.begin();
  92. auto skip_over_whitespace = [&] {
  93. auto prev = it;
  94. while (it != utf8_view.end() && isspace(*it)) {
  95. prev = it;
  96. ++it;
  97. }
  98. it = prev;
  99. };
  100. if (previous_is_empty_or_ends_in_whitespace)
  101. skip_over_whitespace();
  102. for (; it != utf8_view.end(); ++it) {
  103. if (!isspace(*it)) {
  104. builder.append(utf8_view.as_string().characters_without_null_termination() + utf8_view.byte_offset_of(it), it.code_point_length_in_bytes());
  105. } else {
  106. builder.append(' ');
  107. skip_over_whitespace();
  108. }
  109. }
  110. m_text_for_rendering = builder.to_string();
  111. }
  112. void TextNode::split_into_lines_by_rules(InlineFormattingContext& context, LayoutMode layout_mode, bool do_collapse, bool do_wrap_lines, bool do_wrap_breaks)
  113. {
  114. auto& containing_block = context.containing_block();
  115. auto& font = this->font();
  116. auto& line_boxes = containing_block.line_boxes();
  117. containing_block.ensure_last_line_box();
  118. float available_width = context.available_width_at_line(line_boxes.size() - 1) - line_boxes.last().width();
  119. compute_text_for_rendering(do_collapse, line_boxes.last().is_empty_or_ends_in_whitespace());
  120. ChunkIterator iterator(m_text_for_rendering, layout_mode, do_wrap_lines, do_wrap_breaks);
  121. for (;;) {
  122. auto chunk_opt = iterator.next();
  123. if (!chunk_opt.has_value())
  124. break;
  125. auto& chunk = chunk_opt.value();
  126. // Collapse entire fragment into non-existence if previous fragment on line ended in whitespace.
  127. if (do_collapse && line_boxes.last().is_empty_or_ends_in_whitespace() && chunk.is_all_whitespace)
  128. continue;
  129. float chunk_width;
  130. if (do_wrap_lines) {
  131. if (do_collapse && isspace(*chunk.view.begin()) && line_boxes.last().is_empty_or_ends_in_whitespace()) {
  132. // This is a non-empty chunk that starts with collapsible whitespace.
  133. // We are at either at the start of a new line, or after something that ended in whitespace,
  134. // so we don't need to contribute our own whitespace to the line. Skip over it instead!
  135. ++chunk.start;
  136. --chunk.length;
  137. chunk.view = chunk.view.substring_view(1, chunk.view.byte_length() - 1);
  138. }
  139. chunk_width = font.width(chunk.view) + font.glyph_spacing();
  140. if (line_boxes.last().width() > 0 && chunk_width > available_width) {
  141. containing_block.add_line_box();
  142. available_width = context.available_width_at_line(line_boxes.size() - 1);
  143. if (do_collapse && chunk.is_all_whitespace)
  144. continue;
  145. }
  146. } else {
  147. chunk_width = font.width(chunk.view);
  148. }
  149. line_boxes.last().add_fragment(*this, chunk.start, chunk.length, chunk_width, font.glyph_height());
  150. available_width -= chunk_width;
  151. if (do_wrap_lines && available_width < 0) {
  152. containing_block.add_line_box();
  153. available_width = context.available_width_at_line(line_boxes.size() - 1);
  154. }
  155. if (do_wrap_breaks && chunk.has_breaking_newline) {
  156. containing_block.add_line_box();
  157. available_width = context.available_width_at_line(line_boxes.size() - 1);
  158. }
  159. }
  160. }
  161. void TextNode::split_into_lines(InlineFormattingContext& context, LayoutMode layout_mode)
  162. {
  163. bool do_collapse = true;
  164. bool do_wrap_lines = true;
  165. bool do_wrap_breaks = false;
  166. if (computed_values().white_space() == CSS::WhiteSpace::Nowrap) {
  167. do_collapse = true;
  168. do_wrap_lines = false;
  169. do_wrap_breaks = false;
  170. } else if (computed_values().white_space() == CSS::WhiteSpace::Pre) {
  171. do_collapse = false;
  172. do_wrap_lines = false;
  173. do_wrap_breaks = true;
  174. } else if (computed_values().white_space() == CSS::WhiteSpace::PreLine) {
  175. do_collapse = true;
  176. do_wrap_lines = true;
  177. do_wrap_breaks = true;
  178. } else if (computed_values().white_space() == CSS::WhiteSpace::PreWrap) {
  179. do_collapse = false;
  180. do_wrap_lines = true;
  181. do_wrap_breaks = true;
  182. }
  183. split_into_lines_by_rules(context, layout_mode, do_collapse, do_wrap_lines, do_wrap_breaks);
  184. }
  185. bool TextNode::wants_mouse_events() const
  186. {
  187. return parent() && is<Label>(parent());
  188. }
  189. void TextNode::handle_mousedown(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  190. {
  191. if (!parent() || !is<Label>(*parent()))
  192. return;
  193. downcast<Label>(*parent()).handle_mousedown_on_label({}, position, button);
  194. frame().event_handler().set_mouse_event_tracking_layout_node(this);
  195. }
  196. void TextNode::handle_mouseup(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  197. {
  198. if (!parent() || !is<Label>(*parent()))
  199. return;
  200. // NOTE: Changing the state of the DOM node may run arbitrary JS, which could disappear this node.
  201. NonnullRefPtr protect = *this;
  202. downcast<Label>(*parent()).handle_mouseup_on_label({}, position, button);
  203. frame().event_handler().set_mouse_event_tracking_layout_node(nullptr);
  204. }
  205. void TextNode::handle_mousemove(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  206. {
  207. if (!parent() || !is<Label>(*parent()))
  208. return;
  209. downcast<Label>(*parent()).handle_mousemove_on_label({}, position, button);
  210. }
  211. TextNode::ChunkIterator::ChunkIterator(StringView const& text, LayoutMode layout_mode, bool wrap_lines, bool wrap_breaks)
  212. : m_layout_mode(layout_mode)
  213. , m_wrap_lines(wrap_lines)
  214. , m_wrap_breaks(wrap_breaks)
  215. , m_utf8_view(text)
  216. , m_start_of_chunk(m_utf8_view.begin())
  217. , m_iterator(m_utf8_view.begin())
  218. {
  219. m_last_was_space = !text.is_empty() && isspace(*m_utf8_view.begin());
  220. }
  221. Optional<TextNode::Chunk> TextNode::ChunkIterator::next()
  222. {
  223. while (m_iterator != m_utf8_view.end()) {
  224. auto guard = ScopeGuard([&] { ++m_iterator; });
  225. if (m_layout_mode == LayoutMode::AllPossibleLineBreaks) {
  226. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  227. return result.release_value();
  228. }
  229. if (m_last_was_newline) {
  230. m_last_was_newline = false;
  231. if (auto result = try_commit_chunk(m_iterator, true); result.has_value())
  232. return result.release_value();
  233. }
  234. if (m_wrap_breaks && *m_iterator == '\n') {
  235. m_last_was_newline = true;
  236. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  237. return result.release_value();
  238. }
  239. if (m_wrap_lines) {
  240. bool is_space = isspace(*m_iterator);
  241. if (is_space != m_last_was_space) {
  242. m_last_was_space = is_space;
  243. if (auto result = try_commit_chunk(m_iterator, false); result.has_value())
  244. return result.release_value();
  245. }
  246. }
  247. }
  248. if (m_last_was_newline) {
  249. m_last_was_newline = false;
  250. if (auto result = try_commit_chunk(m_utf8_view.end(), true); result.has_value())
  251. return result.release_value();
  252. }
  253. if (m_start_of_chunk != m_utf8_view.end()) {
  254. if (auto result = try_commit_chunk(m_utf8_view.end(), false, true); result.has_value())
  255. return result.release_value();
  256. }
  257. return {};
  258. }
  259. Optional<TextNode::Chunk> TextNode::ChunkIterator::try_commit_chunk(Utf8View::Iterator const& it, bool has_breaking_newline, bool must_commit)
  260. {
  261. if (m_layout_mode == LayoutMode::OnlyRequiredLineBreaks && !must_commit)
  262. return {};
  263. auto start = m_utf8_view.byte_offset_of(m_start_of_chunk);
  264. auto length = m_utf8_view.byte_offset_of(it) - m_utf8_view.byte_offset_of(m_start_of_chunk);
  265. if (has_breaking_newline || length > 0) {
  266. auto chunk_view = m_utf8_view.substring_view(start, length);
  267. m_start_of_chunk = it;
  268. return Chunk {
  269. .view = chunk_view,
  270. .start = start,
  271. .length = length,
  272. .has_breaking_newline = has_breaking_newline,
  273. .is_all_whitespace = is_all_whitespace(chunk_view.as_string()),
  274. };
  275. }
  276. m_start_of_chunk = it;
  277. return {};
  278. }
  279. }