TextNode.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/StringBuilder.h>
  27. #include <AK/Utf8View.h>
  28. #include <LibGfx/Painter.h>
  29. #include <LibWeb/DOM/Document.h>
  30. #include <LibWeb/Layout/BlockBox.h>
  31. #include <LibWeb/Layout/InlineFormattingContext.h>
  32. #include <LibWeb/Layout/Label.h>
  33. #include <LibWeb/Layout/TextNode.h>
  34. #include <LibWeb/Page/Frame.h>
  35. #include <ctype.h>
  36. namespace Web::Layout {
  37. TextNode::TextNode(DOM::Document& document, DOM::Text& text)
  38. : Node(document, &text)
  39. {
  40. set_inline(true);
  41. }
  42. TextNode::~TextNode()
  43. {
  44. }
  45. static bool is_all_whitespace(const StringView& string)
  46. {
  47. for (size_t i = 0; i < string.length(); ++i) {
  48. if (!isspace(string[i]))
  49. return false;
  50. }
  51. return true;
  52. }
  53. void TextNode::paint_fragment(PaintContext& context, const LineBoxFragment& fragment, PaintPhase phase) const
  54. {
  55. auto& painter = context.painter();
  56. if (phase == PaintPhase::Background) {
  57. painter.fill_rect(enclosing_int_rect(fragment.absolute_rect()), computed_values().background_color());
  58. }
  59. if (phase == PaintPhase::Foreground) {
  60. painter.set_font(font());
  61. if (document().inspected_node() == &dom_node())
  62. context.painter().draw_rect(enclosing_int_rect(fragment.absolute_rect()), Color::Magenta);
  63. if (computed_values().text_decoration_line() == CSS::TextDecorationLine::Underline)
  64. 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());
  65. // FIXME: text-transform should be done already in layout, since uppercase glyphs may be wider than lowercase, etc.
  66. auto text = m_text_for_rendering;
  67. auto text_transform = computed_values().text_transform();
  68. if (text_transform == CSS::TextTransform::Uppercase)
  69. text = m_text_for_rendering.to_uppercase();
  70. if (text_transform == CSS::TextTransform::Lowercase)
  71. text = m_text_for_rendering.to_lowercase();
  72. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, computed_values().color());
  73. auto selection_rect = fragment.selection_rect(font());
  74. if (!selection_rect.is_empty()) {
  75. painter.fill_rect(enclosing_int_rect(selection_rect), context.palette().selection());
  76. Gfx::PainterStateSaver saver(painter);
  77. painter.add_clip_rect(enclosing_int_rect(selection_rect));
  78. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, context.palette().selection_text());
  79. }
  80. paint_cursor_if_needed(context, fragment);
  81. }
  82. }
  83. void TextNode::paint_cursor_if_needed(PaintContext& context, const LineBoxFragment& fragment) const
  84. {
  85. if (!frame().is_focused_frame())
  86. return;
  87. if (!frame().cursor_blink_state())
  88. return;
  89. if (frame().cursor_position().node() != &dom_node())
  90. return;
  91. if (!(frame().cursor_position().offset() >= (unsigned)fragment.start() && frame().cursor_position().offset() < (unsigned)(fragment.start() + fragment.length())))
  92. return;
  93. if (!fragment.layout_node().dom_node() || !fragment.layout_node().dom_node()->is_editable())
  94. return;
  95. auto fragment_rect = fragment.absolute_rect();
  96. float cursor_x = fragment_rect.x() + font().width(fragment.text().substring_view(0, frame().cursor_position().offset() - fragment.start()));
  97. float cursor_top = fragment_rect.top();
  98. float cursor_height = fragment_rect.height();
  99. Gfx::IntRect cursor_rect(cursor_x, cursor_top, 1, cursor_height);
  100. context.painter().draw_rect(cursor_rect, computed_values().color());
  101. }
  102. template<typename Callback>
  103. void TextNode::for_each_chunk(Callback callback, LayoutMode layout_mode, bool do_wrap_lines, bool do_wrap_breaks) const
  104. {
  105. Utf8View view(m_text_for_rendering);
  106. if (view.is_empty())
  107. return;
  108. auto start_of_chunk = view.begin();
  109. auto commit_chunk = [&](auto it, bool has_breaking_newline, bool must_commit = false) {
  110. if (layout_mode == LayoutMode::OnlyRequiredLineBreaks && !must_commit)
  111. return;
  112. int start = view.byte_offset_of(start_of_chunk);
  113. int length = view.byte_offset_of(it) - view.byte_offset_of(start_of_chunk);
  114. if (has_breaking_newline || length > 0) {
  115. auto chunk_view = view.substring_view(start, length);
  116. callback(chunk_view, start, length, has_breaking_newline, is_all_whitespace(chunk_view.as_string()));
  117. }
  118. start_of_chunk = it;
  119. };
  120. bool last_was_space = isspace(*view.begin());
  121. bool last_was_newline = false;
  122. for (auto it = view.begin(); it != view.end();) {
  123. if (layout_mode == LayoutMode::AllPossibleLineBreaks) {
  124. commit_chunk(it, false);
  125. }
  126. if (last_was_newline) {
  127. last_was_newline = false;
  128. commit_chunk(it, true);
  129. }
  130. if (do_wrap_breaks && *it == '\n') {
  131. last_was_newline = true;
  132. commit_chunk(it, false);
  133. }
  134. if (do_wrap_lines) {
  135. bool is_space = isspace(*it);
  136. if (is_space != last_was_space) {
  137. last_was_space = is_space;
  138. commit_chunk(it, false);
  139. }
  140. }
  141. ++it;
  142. }
  143. if (last_was_newline)
  144. commit_chunk(view.end(), true);
  145. if (start_of_chunk != view.end())
  146. commit_chunk(view.end(), false, true);
  147. }
  148. void TextNode::split_into_lines_by_rules(InlineFormattingContext& context, LayoutMode layout_mode, bool do_collapse, bool do_wrap_lines, bool do_wrap_breaks)
  149. {
  150. auto& containing_block = context.containing_block();
  151. auto& font = this->font();
  152. auto& line_boxes = containing_block.line_boxes();
  153. containing_block.ensure_last_line_box();
  154. float available_width = context.available_width_at_line(line_boxes.size() - 1) - line_boxes.last().width();
  155. // Collapse whitespace into single spaces
  156. if (do_collapse) {
  157. auto utf8_view = Utf8View(dom_node().data());
  158. StringBuilder builder(dom_node().data().length());
  159. auto it = utf8_view.begin();
  160. auto skip_over_whitespace = [&] {
  161. auto prev = it;
  162. while (it != utf8_view.end() && isspace(*it)) {
  163. prev = it;
  164. ++it;
  165. }
  166. it = prev;
  167. };
  168. if (line_boxes.last().is_empty_or_ends_in_whitespace())
  169. skip_over_whitespace();
  170. for (; it != utf8_view.end(); ++it) {
  171. if (!isspace(*it)) {
  172. builder.append(utf8_view.as_string().characters_without_null_termination() + utf8_view.byte_offset_of(it), it.code_point_length_in_bytes());
  173. } else {
  174. builder.append(' ');
  175. skip_over_whitespace();
  176. }
  177. }
  178. m_text_for_rendering = builder.to_string();
  179. } else {
  180. m_text_for_rendering = dom_node().data();
  181. }
  182. // do_wrap_lines => chunks_are_words
  183. // !do_wrap_lines => chunks_are_lines
  184. struct Chunk {
  185. Utf8View view;
  186. int start { 0 };
  187. int length { 0 };
  188. bool is_break { false };
  189. bool is_all_whitespace { false };
  190. };
  191. Vector<Chunk, 128> chunks;
  192. for_each_chunk(
  193. [&](const Utf8View& view, int start, int length, bool is_break, bool is_all_whitespace) {
  194. chunks.append({ Utf8View(view), start, length, is_break, is_all_whitespace });
  195. },
  196. layout_mode, do_wrap_lines, do_wrap_breaks);
  197. for (size_t i = 0; i < chunks.size(); ++i) {
  198. auto& chunk = chunks[i];
  199. // Collapse entire fragment into non-existence if previous fragment on line ended in whitespace.
  200. if (do_collapse && line_boxes.last().is_empty_or_ends_in_whitespace() && chunk.is_all_whitespace)
  201. continue;
  202. float chunk_width;
  203. if (do_wrap_lines) {
  204. if (do_collapse && isspace(*chunk.view.begin()) && line_boxes.last().is_empty_or_ends_in_whitespace()) {
  205. // This is a non-empty chunk that starts with collapsible whitespace.
  206. // We are at either at the start of a new line, or after something that ended in whitespace,
  207. // so we don't need to contribute our own whitespace to the line. Skip over it instead!
  208. ++chunk.start;
  209. --chunk.length;
  210. chunk.view = chunk.view.substring_view(1, chunk.view.byte_length() - 1);
  211. }
  212. chunk_width = font.width(chunk.view) + font.glyph_spacing();
  213. if (line_boxes.last().width() > 0 && chunk_width > available_width) {
  214. containing_block.add_line_box();
  215. available_width = context.available_width_at_line(line_boxes.size() - 1);
  216. if (do_collapse && chunk.is_all_whitespace)
  217. continue;
  218. }
  219. } else {
  220. chunk_width = font.width(chunk.view);
  221. }
  222. line_boxes.last().add_fragment(*this, chunk.start, chunk.length, chunk_width, font.glyph_height());
  223. available_width -= chunk_width;
  224. if (do_wrap_lines) {
  225. if (available_width < 0) {
  226. containing_block.add_line_box();
  227. available_width = context.available_width_at_line(line_boxes.size() - 1);
  228. }
  229. }
  230. if (do_wrap_breaks) {
  231. if (chunk.is_break) {
  232. containing_block.add_line_box();
  233. available_width = context.available_width_at_line(line_boxes.size() - 1);
  234. }
  235. }
  236. }
  237. }
  238. void TextNode::split_into_lines(InlineFormattingContext& context, LayoutMode layout_mode)
  239. {
  240. bool do_collapse = true;
  241. bool do_wrap_lines = true;
  242. bool do_wrap_breaks = false;
  243. if (computed_values().white_space() == CSS::WhiteSpace::Nowrap) {
  244. do_collapse = true;
  245. do_wrap_lines = false;
  246. do_wrap_breaks = false;
  247. } else if (computed_values().white_space() == CSS::WhiteSpace::Pre) {
  248. do_collapse = false;
  249. do_wrap_lines = false;
  250. do_wrap_breaks = true;
  251. } else if (computed_values().white_space() == CSS::WhiteSpace::PreLine) {
  252. do_collapse = true;
  253. do_wrap_lines = true;
  254. do_wrap_breaks = true;
  255. } else if (computed_values().white_space() == CSS::WhiteSpace::PreWrap) {
  256. do_collapse = false;
  257. do_wrap_lines = true;
  258. do_wrap_breaks = true;
  259. }
  260. split_into_lines_by_rules(context, layout_mode, do_collapse, do_wrap_lines, do_wrap_breaks);
  261. }
  262. bool TextNode::wants_mouse_events() const
  263. {
  264. return parent() && is<Label>(parent());
  265. }
  266. void TextNode::handle_mousedown(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  267. {
  268. if (!parent() || !is<Label>(*parent()))
  269. return;
  270. downcast<Label>(*parent()).handle_mousedown_on_label({}, position, button);
  271. frame().event_handler().set_mouse_event_tracking_layout_node(this);
  272. }
  273. void TextNode::handle_mouseup(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  274. {
  275. if (!parent() || !is<Label>(*parent()))
  276. return;
  277. // NOTE: Changing the state of the DOM node may run arbitrary JS, which could disappear this node.
  278. NonnullRefPtr protect = *this;
  279. downcast<Label>(*parent()).handle_mouseup_on_label({}, position, button);
  280. frame().event_handler().set_mouse_event_tracking_layout_node(nullptr);
  281. }
  282. void TextNode::handle_mousemove(Badge<EventHandler>, const Gfx::IntPoint& position, unsigned button, unsigned)
  283. {
  284. if (!parent() || !is<Label>(*parent()))
  285. return;
  286. downcast<Label>(*parent()).handle_mousemove_on_label({}, position, button);
  287. }
  288. }