TextNode.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibGfx/Painter.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/HTML/BrowsingContext.h>
  12. #include <LibWeb/Layout/BlockContainer.h>
  13. #include <LibWeb/Layout/InlineFormattingContext.h>
  14. #include <LibWeb/Layout/Label.h>
  15. #include <LibWeb/Layout/TextNode.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(StringView string)
  26. {
  27. for (size_t i = 0; i < string.length(); ++i) {
  28. if (!is_ascii_space(string[i]))
  29. return false;
  30. }
  31. return true;
  32. }
  33. void TextNode::paint_text_decoration(Gfx::Painter& painter, LineBoxFragment const& fragment) const
  34. {
  35. Gfx::IntPoint line_start_point {};
  36. Gfx::IntPoint line_end_point {};
  37. auto& font = fragment.layout_node().font();
  38. auto fragment_box = enclosing_int_rect(fragment.absolute_rect());
  39. auto glyph_height = font.glyph_height();
  40. auto baseline = fragment_box.height() / 2 - (glyph_height + 4) / 2 + glyph_height;
  41. switch (computed_values().text_decoration_line()) {
  42. case CSS::TextDecorationLine::None:
  43. return;
  44. case CSS::TextDecorationLine::Underline:
  45. line_start_point = fragment_box.top_left().translated(0, baseline + 2);
  46. line_end_point = fragment_box.top_right().translated(0, baseline + 2);
  47. break;
  48. case CSS::TextDecorationLine::Overline:
  49. line_start_point = fragment_box.top_left().translated(0, baseline - glyph_height);
  50. line_end_point = fragment_box.top_right().translated(0, baseline - glyph_height);
  51. break;
  52. case CSS::TextDecorationLine::LineThrough: {
  53. auto x_height = font.x_height();
  54. line_start_point = fragment_box.top_left().translated(0, baseline - x_height / 2);
  55. line_end_point = fragment_box.top_right().translated(0, baseline - x_height / 2);
  56. break;
  57. }
  58. case CSS::TextDecorationLine::Blink:
  59. // Conforming user agents may simply not blink the text
  60. return;
  61. }
  62. auto line_color = computed_values().text_decoration_color();
  63. switch (computed_values().text_decoration_style()) {
  64. // FIXME: Implement the other styles
  65. case CSS::TextDecorationStyle::Solid:
  66. case CSS::TextDecorationStyle::Double:
  67. case CSS::TextDecorationStyle::Dashed:
  68. case CSS::TextDecorationStyle::Dotted:
  69. painter.draw_line(line_start_point, line_end_point, line_color);
  70. break;
  71. case CSS::TextDecorationStyle::Wavy:
  72. // FIXME: There is a thing called text-decoration-thickness which also affects the amplitude here.
  73. painter.draw_triangle_wave(line_start_point, line_end_point, line_color, 2);
  74. break;
  75. }
  76. }
  77. void TextNode::paint_fragment(PaintContext& context, const LineBoxFragment& fragment, PaintPhase phase) const
  78. {
  79. auto& painter = context.painter();
  80. if (phase == PaintPhase::Foreground) {
  81. auto fragment_absolute_rect = fragment.absolute_rect();
  82. painter.set_font(font());
  83. if (document().inspected_node() == &dom_node())
  84. context.painter().draw_rect(enclosing_int_rect(fragment_absolute_rect), Color::Magenta);
  85. paint_text_decoration(painter, fragment);
  86. // FIXME: text-transform should be done already in layout, since uppercase glyphs may be wider than lowercase, etc.
  87. auto text = m_text_for_rendering;
  88. auto text_transform = computed_values().text_transform();
  89. if (text_transform == CSS::TextTransform::Uppercase)
  90. text = m_text_for_rendering.to_uppercase();
  91. if (text_transform == CSS::TextTransform::Lowercase)
  92. text = m_text_for_rendering.to_lowercase();
  93. // FIXME: This is a hack to prevent text clipping when painting a bitmap font into a too-small box.
  94. auto draw_rect = enclosing_int_rect(fragment_absolute_rect);
  95. draw_rect.set_height(max(draw_rect.height(), font().glyph_height()));
  96. painter.draw_text(draw_rect, text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, computed_values().color());
  97. auto selection_rect = fragment.selection_rect(font());
  98. if (!selection_rect.is_empty()) {
  99. painter.fill_rect(enclosing_int_rect(selection_rect), context.palette().selection());
  100. Gfx::PainterStateSaver saver(painter);
  101. painter.add_clip_rect(enclosing_int_rect(selection_rect));
  102. painter.draw_text(enclosing_int_rect(fragment_absolute_rect), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, context.palette().selection_text());
  103. }
  104. paint_cursor_if_needed(context, fragment);
  105. }
  106. }
  107. void TextNode::paint_cursor_if_needed(PaintContext& context, const LineBoxFragment& fragment) const
  108. {
  109. if (!browsing_context().is_focused_context())
  110. return;
  111. if (!browsing_context().cursor_blink_state())
  112. return;
  113. if (browsing_context().cursor_position().node() != &dom_node())
  114. return;
  115. // 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.
  116. if (browsing_context().cursor_position().offset() < (unsigned)fragment.start() || browsing_context().cursor_position().offset() > (unsigned)(fragment.start() + fragment.length()))
  117. return;
  118. if (!fragment.layout_node().dom_node() || !fragment.layout_node().dom_node()->is_editable())
  119. return;
  120. auto fragment_rect = fragment.absolute_rect();
  121. float cursor_x = fragment_rect.x() + font().width(fragment.text().substring_view(0, browsing_context().cursor_position().offset() - fragment.start()));
  122. float cursor_top = fragment_rect.top();
  123. float cursor_height = fragment_rect.height();
  124. Gfx::IntRect cursor_rect(cursor_x, cursor_top, 1, cursor_height);
  125. context.painter().draw_rect(cursor_rect, computed_values().color());
  126. }
  127. // NOTE: This collapes whitespace into a single ASCII space if collapse is true. If previous_is_empty_or_ends_in_whitespace, it also strips leading whitespace.
  128. void TextNode::compute_text_for_rendering(bool collapse, bool previous_is_empty_or_ends_in_whitespace)
  129. {
  130. auto& data = dom_node().data();
  131. if (!collapse || data.is_empty()) {
  132. m_text_for_rendering = data;
  133. return;
  134. }
  135. // NOTE: A couple fast returns to avoid unnecessarily allocating a StringBuilder.
  136. if (data.length() == 1) {
  137. if (is_ascii_space(data[0])) {
  138. if (previous_is_empty_or_ends_in_whitespace)
  139. m_text_for_rendering = String::empty();
  140. else {
  141. static String s_single_space_string = " ";
  142. m_text_for_rendering = s_single_space_string;
  143. }
  144. } else {
  145. m_text_for_rendering = data;
  146. }
  147. return;
  148. }
  149. bool contains_space = false;
  150. for (auto& c : data) {
  151. if (is_ascii_space(c)) {
  152. contains_space = true;
  153. break;
  154. }
  155. }
  156. if (!contains_space) {
  157. m_text_for_rendering = data;
  158. return;
  159. }
  160. StringBuilder builder(data.length());
  161. size_t index = 0;
  162. auto skip_over_whitespace = [&index, &data] {
  163. while (index < data.length() && is_ascii_space(data[index]))
  164. ++index;
  165. };
  166. if (previous_is_empty_or_ends_in_whitespace)
  167. skip_over_whitespace();
  168. while (index < data.length()) {
  169. if (is_ascii_space(data[index])) {
  170. builder.append(' ');
  171. ++index;
  172. skip_over_whitespace();
  173. } else {
  174. builder.append(data[index]);
  175. ++index;
  176. }
  177. }
  178. m_text_for_rendering = builder.to_string();
  179. }
  180. bool TextNode::wants_mouse_events() const
  181. {
  182. return first_ancestor_of_type<Label>();
  183. }
  184. void TextNode::handle_mousedown(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  185. {
  186. auto* label = first_ancestor_of_type<Label>();
  187. if (!label)
  188. return;
  189. label->handle_mousedown_on_label({}, position, button);
  190. browsing_context().event_handler().set_mouse_event_tracking_layout_node(this);
  191. }
  192. void TextNode::handle_mouseup(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  193. {
  194. auto* label = first_ancestor_of_type<Label>();
  195. if (!label)
  196. return;
  197. // NOTE: Changing the state of the DOM node may run arbitrary JS, which could disappear this node.
  198. NonnullRefPtr protect = *this;
  199. label->handle_mouseup_on_label({}, position, button);
  200. browsing_context().event_handler().set_mouse_event_tracking_layout_node(nullptr);
  201. }
  202. void TextNode::handle_mousemove(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  203. {
  204. auto* label = first_ancestor_of_type<Label>();
  205. if (!label)
  206. return;
  207. label->handle_mousemove_on_label({}, position, button);
  208. }
  209. TextNode::ChunkIterator::ChunkIterator(StringView text, LayoutMode layout_mode, bool wrap_lines, bool respect_linebreaks)
  210. : m_layout_mode(layout_mode)
  211. , m_wrap_lines(wrap_lines)
  212. , m_respect_linebreaks(respect_linebreaks)
  213. , m_utf8_view(text)
  214. , m_iterator(m_utf8_view.begin())
  215. {
  216. m_last_was_space = !text.is_empty() && is_ascii_space(*m_utf8_view.begin());
  217. }
  218. Optional<TextNode::Chunk> TextNode::ChunkIterator::next()
  219. {
  220. if (m_iterator == m_utf8_view.end())
  221. return {};
  222. auto start_of_chunk = m_iterator;
  223. while (m_iterator != m_utf8_view.end()) {
  224. ++m_iterator;
  225. if (m_last_was_newline) {
  226. // NOTE: This expression looks out for the case where we have
  227. // multiple newlines in a row. Because every output next()
  228. // that's a newline newline must be prepared for in advance by
  229. // the previous next() call, we need to check whether the next
  230. // character is a newline here as well. Otherwise, the newline
  231. // becomes part of the next expression and causes rendering
  232. // issues.
  233. m_last_was_newline = m_iterator != m_utf8_view.end() && *m_iterator == '\n';
  234. if (auto result = try_commit_chunk(start_of_chunk, m_iterator, true); result.has_value())
  235. return result.release_value();
  236. }
  237. // NOTE: The checks after this need to look at the current iterator
  238. // position, which depends on not being at the end.
  239. if (m_iterator == m_utf8_view.end())
  240. break;
  241. // NOTE: When we're supposed to stop on linebreaks, we're actually
  242. // supposed to output two chunks: "content" and "\n". Since we
  243. // can't output two chunks at once, we store this information as a
  244. // flag to output the newline immediately at the earliest
  245. // opportunity.
  246. if (m_respect_linebreaks && *m_iterator == '\n') {
  247. m_last_was_newline = true;
  248. if (auto result = try_commit_chunk(start_of_chunk, m_iterator, false); result.has_value()) {
  249. return result.release_value();
  250. }
  251. }
  252. if (m_wrap_lines || m_layout_mode == LayoutMode::AllPossibleLineBreaks) {
  253. bool is_space = is_ascii_space(*m_iterator);
  254. if (is_space != m_last_was_space) {
  255. m_last_was_space = is_space;
  256. if (auto result = try_commit_chunk(start_of_chunk, m_iterator, false); result.has_value()) {
  257. return result.release_value();
  258. }
  259. }
  260. }
  261. }
  262. if (start_of_chunk != m_utf8_view.end()) {
  263. // Try to output whatever's left at the end of the text node.
  264. if (auto result = try_commit_chunk(start_of_chunk, m_utf8_view.end(), false, true); result.has_value())
  265. return result.release_value();
  266. }
  267. return {};
  268. }
  269. Optional<TextNode::Chunk> TextNode::ChunkIterator::try_commit_chunk(Utf8View::Iterator const& start, Utf8View::Iterator const& end, bool has_breaking_newline, bool must_commit)
  270. {
  271. if (m_layout_mode == LayoutMode::OnlyRequiredLineBreaks && !must_commit)
  272. return {};
  273. auto byte_offset = m_utf8_view.byte_offset_of(start);
  274. auto byte_length = m_utf8_view.byte_offset_of(end) - byte_offset;
  275. if (byte_length > 0) {
  276. auto chunk_view = m_utf8_view.substring_view(byte_offset, byte_length);
  277. return Chunk {
  278. .view = chunk_view,
  279. .start = byte_offset,
  280. .length = byte_length,
  281. .has_breaking_newline = has_breaking_newline,
  282. .is_all_whitespace = is_all_whitespace(chunk_view.as_string()),
  283. };
  284. }
  285. return {};
  286. }
  287. void TextNode::paint(PaintContext&, PaintPhase)
  288. {
  289. }
  290. }