TextNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 <LibCore/DirIterator.h>
  29. #include <LibGUI/Painter.h>
  30. #include <LibGfx/Font.h>
  31. #include <LibWeb/DOM/Document.h>
  32. #include <LibWeb/Layout/BlockBox.h>
  33. #include <LibWeb/Layout/InlineFormattingContext.h>
  34. #include <LibWeb/Layout/TextNode.h>
  35. #include <LibWeb/Page/Frame.h>
  36. #include <ctype.h>
  37. namespace Web::Layout {
  38. TextNode::TextNode(DOM::Document& document, DOM::Text& text)
  39. : Node(document, &text)
  40. {
  41. set_inline(true);
  42. }
  43. TextNode::~TextNode()
  44. {
  45. }
  46. static bool is_all_whitespace(const StringView& string)
  47. {
  48. for (size_t i = 0; i < string.length(); ++i) {
  49. if (!isspace(string[i]))
  50. return false;
  51. }
  52. return true;
  53. }
  54. const String& TextNode::text_for_style(const CSS::StyleProperties& style) const
  55. {
  56. static String one_space = " ";
  57. if (is_all_whitespace(dom_node().data())) {
  58. if (style.white_space().value_or(CSS::WhiteSpace::Normal) == CSS::WhiteSpace::Normal)
  59. return one_space;
  60. }
  61. return dom_node().data();
  62. }
  63. void TextNode::paint_fragment(PaintContext& context, const LineBoxFragment& fragment, PaintPhase phase) const
  64. {
  65. auto& painter = context.painter();
  66. if (phase == PaintPhase::Background) {
  67. auto background_color = specified_style().property(CSS::PropertyID::BackgroundColor);
  68. if (background_color.has_value() && background_color.value()->is_color())
  69. painter.fill_rect(enclosing_int_rect(fragment.absolute_rect()), background_color.value()->to_color(document()));
  70. }
  71. if (phase == PaintPhase::Foreground) {
  72. painter.set_font(specified_style().font());
  73. auto color = specified_style().color_or_fallback(CSS::PropertyID::Color, document(), context.palette().base_text());
  74. auto text_decoration = specified_style().string_or_fallback(CSS::PropertyID::TextDecoration, "none");
  75. if (document().inspected_node() == &dom_node())
  76. context.painter().draw_rect(enclosing_int_rect(fragment.absolute_rect()), Color::Magenta);
  77. bool is_underline = text_decoration == "underline";
  78. if (is_underline)
  79. 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), color);
  80. // FIXME: text-transform should be done already in layout, since uppercase glyphs may be wider than lowercase, etc.
  81. auto text = m_text_for_rendering;
  82. auto text_transform = specified_style().string_or_fallback(CSS::PropertyID::TextTransform, "none");
  83. if (text_transform == "uppercase")
  84. text = m_text_for_rendering.to_uppercase();
  85. if (text_transform == "lowercase")
  86. text = m_text_for_rendering.to_lowercase();
  87. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, color);
  88. auto selection_rect = fragment.selection_rect(specified_style().font());
  89. if (!selection_rect.is_empty()) {
  90. painter.fill_rect(enclosing_int_rect(selection_rect), context.palette().selection());
  91. Gfx::PainterStateSaver saver(painter);
  92. painter.add_clip_rect(enclosing_int_rect(selection_rect));
  93. painter.draw_text(enclosing_int_rect(fragment.absolute_rect()), text.substring_view(fragment.start(), fragment.length()), Gfx::TextAlignment::CenterLeft, context.palette().selection_text());
  94. }
  95. paint_cursor_if_needed(context, fragment);
  96. }
  97. }
  98. void TextNode::paint_cursor_if_needed(PaintContext& context, const LineBoxFragment& fragment) const
  99. {
  100. if (!frame().is_focused_frame())
  101. return;
  102. if (!frame().cursor_blink_state())
  103. return;
  104. if (frame().cursor_position().node() != &dom_node())
  105. return;
  106. if (!(frame().cursor_position().offset() >= (unsigned)fragment.start() && frame().cursor_position().offset() < (unsigned)(fragment.start() + fragment.length())))
  107. return;
  108. if (!fragment.layout_node().dom_node() || !fragment.layout_node().dom_node()->is_editable())
  109. return;
  110. auto fragment_rect = fragment.absolute_rect();
  111. float cursor_x = fragment_rect.x() + specified_style().font().width(fragment.text().substring_view(0, frame().cursor_position().offset() - fragment.start()));
  112. float cursor_top = fragment_rect.top();
  113. float cursor_height = fragment_rect.height();
  114. Gfx::IntRect cursor_rect(cursor_x, cursor_top, 1, cursor_height);
  115. auto color = specified_style().color_or_fallback(CSS::PropertyID::Color, document(), context.palette().base_text());
  116. context.painter().draw_rect(cursor_rect, color);
  117. }
  118. template<typename Callback>
  119. void TextNode::for_each_chunk(Callback callback, LayoutMode layout_mode, bool do_wrap_lines, bool do_wrap_breaks) const
  120. {
  121. Utf8View view(m_text_for_rendering);
  122. if (view.is_empty())
  123. return;
  124. auto start_of_chunk = view.begin();
  125. auto commit_chunk = [&](auto it, bool has_breaking_newline, bool must_commit = false) {
  126. if (layout_mode == LayoutMode::OnlyRequiredLineBreaks && !must_commit)
  127. return;
  128. int start = view.byte_offset_of(start_of_chunk);
  129. int length = view.byte_offset_of(it) - view.byte_offset_of(start_of_chunk);
  130. if (has_breaking_newline || length > 0) {
  131. auto chunk_view = view.substring_view(start, length);
  132. callback(chunk_view, start, length, has_breaking_newline, is_all_whitespace(chunk_view.as_string()));
  133. }
  134. start_of_chunk = it;
  135. };
  136. bool last_was_space = isspace(*view.begin());
  137. bool last_was_newline = false;
  138. for (auto it = view.begin(); it != view.end();) {
  139. if (layout_mode == LayoutMode::AllPossibleLineBreaks) {
  140. commit_chunk(it, false);
  141. }
  142. if (last_was_newline) {
  143. last_was_newline = false;
  144. commit_chunk(it, true);
  145. }
  146. if (do_wrap_breaks && *it == '\n') {
  147. last_was_newline = true;
  148. commit_chunk(it, false);
  149. }
  150. if (do_wrap_lines) {
  151. bool is_space = isspace(*it);
  152. if (is_space != last_was_space) {
  153. last_was_space = is_space;
  154. commit_chunk(it, false);
  155. }
  156. }
  157. ++it;
  158. }
  159. if (last_was_newline)
  160. commit_chunk(view.end(), true);
  161. if (start_of_chunk != view.end())
  162. commit_chunk(view.end(), false, true);
  163. }
  164. void TextNode::split_into_lines_by_rules(InlineFormattingContext& context, LayoutMode layout_mode, bool do_collapse, bool do_wrap_lines, bool do_wrap_breaks)
  165. {
  166. auto& containing_block = context.containing_block();
  167. auto& font = specified_style().font();
  168. float space_width = font.glyph_width(' ') + font.glyph_spacing();
  169. auto& line_boxes = containing_block.line_boxes();
  170. containing_block.ensure_last_line_box();
  171. float available_width = context.available_width_at_line(line_boxes.size() - 1) - line_boxes.last().width();
  172. // Collapse whitespace into single spaces
  173. if (do_collapse) {
  174. auto utf8_view = Utf8View(dom_node().data());
  175. StringBuilder builder(dom_node().data().length());
  176. auto it = utf8_view.begin();
  177. auto skip_over_whitespace = [&] {
  178. auto prev = it;
  179. while (it != utf8_view.end() && isspace(*it)) {
  180. prev = it;
  181. ++it;
  182. }
  183. it = prev;
  184. };
  185. if (line_boxes.last().ends_in_whitespace())
  186. skip_over_whitespace();
  187. for (; it != utf8_view.end(); ++it) {
  188. if (!isspace(*it)) {
  189. builder.append(utf8_view.as_string().characters_without_null_termination() + utf8_view.byte_offset_of(it), it.code_point_length_in_bytes());
  190. } else {
  191. builder.append(' ');
  192. skip_over_whitespace();
  193. }
  194. }
  195. m_text_for_rendering = builder.to_string();
  196. } else {
  197. m_text_for_rendering = dom_node().data();
  198. }
  199. // do_wrap_lines => chunks_are_words
  200. // !do_wrap_lines => chunks_are_lines
  201. struct Chunk {
  202. Utf8View view;
  203. int start { 0 };
  204. int length { 0 };
  205. bool is_break { false };
  206. bool is_all_whitespace { false };
  207. };
  208. Vector<Chunk, 128> chunks;
  209. for_each_chunk(
  210. [&](const Utf8View& view, int start, int length, bool is_break, bool is_all_whitespace) {
  211. chunks.append({ Utf8View(view), start, length, is_break, is_all_whitespace });
  212. },
  213. layout_mode, do_wrap_lines, do_wrap_breaks);
  214. for (size_t i = 0; i < chunks.size(); ++i) {
  215. auto& chunk = chunks[i];
  216. // Collapse entire fragment into non-existence if previous fragment on line ended in whitespace.
  217. if (do_collapse && line_boxes.last().ends_in_whitespace() && chunk.is_all_whitespace)
  218. continue;
  219. float chunk_width;
  220. bool need_collapse = false;
  221. if (do_wrap_lines) {
  222. need_collapse = do_collapse && isspace(*chunk.view.begin()) && line_boxes.last().ends_in_whitespace();
  223. if (need_collapse)
  224. chunk_width = space_width;
  225. else
  226. chunk_width = font.width(chunk.view) + font.glyph_spacing();
  227. if (line_boxes.last().width() > 0 && chunk_width > available_width) {
  228. containing_block.add_line_box();
  229. available_width = context.available_width_at_line(line_boxes.size() - 1);
  230. }
  231. if (need_collapse & line_boxes.last().fragments().is_empty())
  232. continue;
  233. } else {
  234. chunk_width = font.width(chunk.view);
  235. }
  236. line_boxes.last().add_fragment(*this, chunk.start, need_collapse ? 1 : chunk.length, chunk_width, font.glyph_height());
  237. available_width -= chunk_width;
  238. if (do_wrap_lines) {
  239. if (available_width < 0) {
  240. containing_block.add_line_box();
  241. available_width = context.available_width_at_line(line_boxes.size() - 1);
  242. }
  243. }
  244. if (do_wrap_breaks) {
  245. if (chunk.is_break) {
  246. containing_block.add_line_box();
  247. available_width = context.available_width_at_line(line_boxes.size() - 1);
  248. }
  249. }
  250. }
  251. }
  252. void TextNode::split_into_lines(InlineFormattingContext& context, LayoutMode layout_mode)
  253. {
  254. bool do_collapse = true;
  255. bool do_wrap_lines = true;
  256. bool do_wrap_breaks = false;
  257. if (style().white_space() == CSS::WhiteSpace::Nowrap) {
  258. do_collapse = true;
  259. do_wrap_lines = false;
  260. do_wrap_breaks = false;
  261. } else if (style().white_space() == CSS::WhiteSpace::Pre) {
  262. do_collapse = false;
  263. do_wrap_lines = false;
  264. do_wrap_breaks = true;
  265. } else if (style().white_space() == CSS::WhiteSpace::PreLine) {
  266. do_collapse = true;
  267. do_wrap_lines = true;
  268. do_wrap_breaks = true;
  269. } else if (style().white_space() == CSS::WhiteSpace::PreWrap) {
  270. do_collapse = false;
  271. do_wrap_lines = true;
  272. do_wrap_breaks = true;
  273. }
  274. split_into_lines_by_rules(context, layout_mode, do_collapse, do_wrap_lines, do_wrap_breaks);
  275. }
  276. }