LayoutBlock.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 <LibGUI/Painter.h>
  27. #include <LibWeb/CSS/StyleResolver.h>
  28. #include <LibWeb/DOM/Element.h>
  29. #include <LibWeb/Layout/LayoutBlock.h>
  30. #include <LibWeb/Layout/LayoutInline.h>
  31. #include <LibWeb/Layout/LayoutReplaced.h>
  32. #include <LibWeb/Layout/LayoutText.h>
  33. #include <math.h>
  34. namespace Web {
  35. LayoutBlock::LayoutBlock(const Node* node, NonnullRefPtr<StyleProperties> style)
  36. : LayoutBox(node, move(style))
  37. {
  38. }
  39. LayoutBlock::~LayoutBlock()
  40. {
  41. }
  42. LayoutNode& LayoutBlock::inline_wrapper()
  43. {
  44. if (!last_child() || !last_child()->is_block() || last_child()->node() != nullptr) {
  45. append_child(adopt(*new LayoutBlock(nullptr, style_for_anonymous_block())));
  46. last_child()->set_children_are_inline(true);
  47. }
  48. return *last_child();
  49. }
  50. void LayoutBlock::layout(LayoutMode layout_mode)
  51. {
  52. compute_width();
  53. if (!is_inline())
  54. compute_position();
  55. layout_children(layout_mode);
  56. compute_height();
  57. }
  58. void LayoutBlock::layout_children(LayoutMode layout_mode)
  59. {
  60. if (children_are_inline())
  61. layout_inline_children(layout_mode);
  62. else
  63. layout_block_children(layout_mode);
  64. }
  65. void LayoutBlock::layout_block_children(LayoutMode layout_mode)
  66. {
  67. ASSERT(!children_are_inline());
  68. float content_height = 0;
  69. for_each_child([&](auto& child) {
  70. // FIXME: What should we do here? Something like a <table> might have a bunch of useless text children..
  71. if (child.is_inline())
  72. return;
  73. auto& child_block = static_cast<LayoutBlock&>(child);
  74. child_block.layout(layout_mode);
  75. content_height = child_block.rect().bottom() + child_block.box_model().full_margin().bottom - rect().top();
  76. });
  77. if (layout_mode != LayoutMode::Default) {
  78. float max_width = 0;
  79. for_each_child([&](auto& child) {
  80. if (child.is_box())
  81. max_width = max(max_width, to<LayoutBox>(child).width());
  82. });
  83. rect().set_width(max_width);
  84. }
  85. rect().set_height(content_height);
  86. }
  87. void LayoutBlock::layout_inline_children(LayoutMode layout_mode)
  88. {
  89. ASSERT(children_are_inline());
  90. m_line_boxes.clear();
  91. for_each_child([&](auto& child) {
  92. ASSERT(child.is_inline());
  93. child.split_into_lines(*this, layout_mode);
  94. });
  95. for (auto& line_box : m_line_boxes) {
  96. line_box.trim_trailing_whitespace();
  97. }
  98. float min_line_height = style().line_height();
  99. float line_spacing = min_line_height - style().font().glyph_height();
  100. float content_height = 0;
  101. // FIXME: This should be done by the CSS parser!
  102. CSS::ValueID text_align = CSS::ValueID::Left;
  103. auto text_align_string = style().string_or_fallback(CSS::PropertyID::TextAlign, "left");
  104. if (text_align_string == "center")
  105. text_align = CSS::ValueID::Center;
  106. else if (text_align_string == "left")
  107. text_align = CSS::ValueID::Left;
  108. else if (text_align_string == "right")
  109. text_align = CSS::ValueID::Right;
  110. else if (text_align_string == "justify")
  111. text_align = CSS::ValueID::Justify;
  112. float max_linebox_width = 0;
  113. for (auto& line_box : m_line_boxes) {
  114. float max_height = min_line_height;
  115. for (auto& fragment : line_box.fragments()) {
  116. max_height = max(max_height, fragment.rect().height());
  117. }
  118. float x_offset = x();
  119. float excess_horizontal_space = (float)width() - line_box.width();
  120. switch (text_align) {
  121. case CSS::ValueID::Center:
  122. x_offset += excess_horizontal_space / 2;
  123. break;
  124. case CSS::ValueID::Right:
  125. x_offset += excess_horizontal_space;
  126. break;
  127. case CSS::ValueID::Left:
  128. case CSS::ValueID::Justify:
  129. default:
  130. break;
  131. }
  132. float excess_horizontal_space_including_whitespace = excess_horizontal_space;
  133. int whitespace_count = 0;
  134. if (text_align == CSS::ValueID::Justify) {
  135. for (auto& fragment : line_box.fragments()) {
  136. if (fragment.is_justifiable_whitespace()) {
  137. ++whitespace_count;
  138. excess_horizontal_space_including_whitespace += fragment.rect().width();
  139. }
  140. }
  141. }
  142. float justified_space_width = whitespace_count ? (excess_horizontal_space_including_whitespace / (float)whitespace_count) : 0;
  143. for (size_t i = 0; i < line_box.fragments().size(); ++i) {
  144. auto& fragment = line_box.fragments()[i];
  145. // Vertically align everyone's bottom to the line.
  146. // FIXME: Support other kinds of vertical alignment.
  147. fragment.rect().set_x(roundf(x_offset + fragment.rect().x()));
  148. fragment.rect().set_y(y() + content_height + (max_height - fragment.rect().height()) - (line_spacing / 2));
  149. if (text_align == CSS::ValueID::Justify) {
  150. if (fragment.is_justifiable_whitespace()) {
  151. if (fragment.rect().width() != justified_space_width) {
  152. float diff = justified_space_width - fragment.rect().width();
  153. fragment.rect().set_width(justified_space_width);
  154. // Shift subsequent sibling fragments to the right to adjust for change in width.
  155. for (size_t j = i + 1; j < line_box.fragments().size(); ++j) {
  156. line_box.fragments()[j].rect().move_by(diff, 0);
  157. }
  158. }
  159. }
  160. }
  161. if (is<LayoutReplaced>(fragment.layout_node()))
  162. const_cast<LayoutReplaced&>(to<LayoutReplaced>(fragment.layout_node())).set_rect(fragment.rect());
  163. if (fragment.layout_node().is_inline_block()) {
  164. auto& inline_block = const_cast<LayoutBlock&>(to<LayoutBlock>(fragment.layout_node()));
  165. inline_block.set_rect(fragment.rect());
  166. inline_block.layout(layout_mode);
  167. }
  168. float final_line_box_width = 0;
  169. for (auto& fragment : line_box.fragments())
  170. final_line_box_width += fragment.rect().width();
  171. line_box.m_width = final_line_box_width;
  172. max_linebox_width = max(max_linebox_width, final_line_box_width);
  173. }
  174. content_height += max_height;
  175. }
  176. if (layout_mode != LayoutMode::Default) {
  177. rect().set_width(max_linebox_width);
  178. }
  179. rect().set_height(content_height);
  180. }
  181. void LayoutBlock::compute_width()
  182. {
  183. auto& style = this->style();
  184. auto auto_value = Length();
  185. auto zero_value = Length(0, Length::Type::Absolute);
  186. Length margin_left;
  187. Length margin_right;
  188. Length border_left;
  189. Length border_right;
  190. Length padding_left;
  191. Length padding_right;
  192. auto& containing_block = *this->containing_block();
  193. auto try_compute_width = [&](const auto& a_width) {
  194. Length width = a_width;
  195. #ifdef HTML_DEBUG
  196. dbg() << " Left: " << margin_left << "+" << border_left << "+" << padding_left;
  197. dbg() << "Right: " << margin_right << "+" << border_right << "+" << padding_right;
  198. #endif
  199. margin_left = style.length_or_fallback(CSS::PropertyID::MarginLeft, zero_value, containing_block.width());
  200. margin_right = style.length_or_fallback(CSS::PropertyID::MarginRight, zero_value, containing_block.width());
  201. border_left = style.length_or_fallback(CSS::PropertyID::BorderLeftWidth, zero_value);
  202. border_right = style.length_or_fallback(CSS::PropertyID::BorderRightWidth, zero_value);
  203. padding_left = style.length_or_fallback(CSS::PropertyID::PaddingLeft, zero_value, containing_block.width());
  204. padding_right = style.length_or_fallback(CSS::PropertyID::PaddingRight, zero_value, containing_block.width());
  205. float total_px = 0;
  206. for (auto& value : { margin_left, border_left, padding_left, width, padding_right, border_right, margin_right }) {
  207. total_px += value.to_px();
  208. }
  209. #ifdef HTML_DEBUG
  210. dbg() << "Total: " << total_px;
  211. #endif
  212. if (!is_replaced() && !is_inline()) {
  213. // 10.3.3 Block-level, non-replaced elements in normal flow
  214. // If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto' values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
  215. if (width.is_auto() && total_px > containing_block.width()) {
  216. if (margin_left.is_auto())
  217. margin_left = zero_value;
  218. if (margin_right.is_auto())
  219. margin_right = zero_value;
  220. }
  221. // 10.3.3 cont'd.
  222. auto underflow_px = containing_block.width() - total_px;
  223. if (width.is_auto()) {
  224. if (margin_left.is_auto())
  225. margin_left = zero_value;
  226. if (margin_right.is_auto())
  227. margin_right = zero_value;
  228. if (underflow_px >= 0) {
  229. width = Length(underflow_px, Length::Type::Absolute);
  230. } else {
  231. width = zero_value;
  232. margin_right = Length(margin_right.to_px() + underflow_px, Length::Type::Absolute);
  233. }
  234. } else {
  235. if (!margin_left.is_auto() && !margin_right.is_auto()) {
  236. margin_right = Length(margin_right.to_px() + underflow_px, Length::Type::Absolute);
  237. } else if (!margin_left.is_auto() && margin_right.is_auto()) {
  238. margin_right = Length(underflow_px, Length::Type::Absolute);
  239. } else if (margin_left.is_auto() && !margin_right.is_auto()) {
  240. margin_left = Length(underflow_px, Length::Type::Absolute);
  241. } else { // margin_left.is_auto() && margin_right.is_auto()
  242. auto half_of_the_underflow = Length(underflow_px / 2, Length::Type::Absolute);
  243. margin_left = half_of_the_underflow;
  244. margin_right = half_of_the_underflow;
  245. }
  246. }
  247. } else if (!is_replaced() && is_inline_block()) {
  248. // 10.3.9 'Inline-block', non-replaced elements in normal flow
  249. // A computed value of 'auto' for 'margin-left' or 'margin-right' becomes a used value of '0'.
  250. if (margin_left.is_auto())
  251. margin_left = zero_value;
  252. if (margin_right.is_auto())
  253. margin_right = zero_value;
  254. // If 'width' is 'auto', the used value is the shrink-to-fit width as for floating elements.
  255. if (width.is_auto()) {
  256. auto greatest_child_width = [&] {
  257. float max_width = 0;
  258. if (children_are_inline()) {
  259. for (auto& box : line_boxes()) {
  260. max_width = max(max_width, box.width());
  261. }
  262. } else {
  263. for_each_child([&](auto& child) {
  264. if (child.is_box())
  265. max_width = max(max_width, to<LayoutBox>(child).width());
  266. });
  267. }
  268. return max_width;
  269. };
  270. // Find the available width: in this case, this is the width of the containing
  271. // block minus the used values of 'margin-left', 'border-left-width', 'padding-left',
  272. // 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.
  273. float available_width = containing_block.width()
  274. - margin_left.to_px() - border_left.to_px() - padding_left.to_px()
  275. - padding_right.to_px() - border_right.to_px() - margin_right.to_px();
  276. // Calculate the preferred width by formatting the content without breaking lines
  277. // other than where explicit line breaks occur.
  278. layout_children(LayoutMode::OnlyRequiredLineBreaks);
  279. float preferred_width = greatest_child_width();
  280. // Also calculate the preferred minimum width, e.g., by trying all possible line breaks.
  281. // CSS 2.2 does not define the exact algorithm.
  282. layout_children(LayoutMode::AllPossibleLineBreaks);
  283. float preferred_minimum_width = greatest_child_width();
  284. // Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).
  285. width = Length(min(max(preferred_minimum_width, available_width), preferred_width), Length::Type::Absolute);
  286. }
  287. }
  288. return width;
  289. };
  290. auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, auto_value, containing_block.width());
  291. // 1. The tentative used width is calculated (without 'min-width' and 'max-width')
  292. auto used_width = try_compute_width(specified_width);
  293. // 2. The tentative used width is greater than 'max-width', the rules above are applied again,
  294. // but this time using the computed value of 'max-width' as the computed value for 'width'.
  295. auto specified_max_width = style.length_or_fallback(CSS::PropertyID::MaxWidth, auto_value, containing_block.width());
  296. if (!specified_max_width.is_auto()) {
  297. if (used_width.to_px() > specified_max_width.to_px()) {
  298. used_width = try_compute_width(specified_max_width);
  299. }
  300. }
  301. // 3. If the resulting width is smaller than 'min-width', the rules above are applied again,
  302. // but this time using the value of 'min-width' as the computed value for 'width'.
  303. auto specified_min_width = style.length_or_fallback(CSS::PropertyID::MinWidth, auto_value, containing_block.width());
  304. if (!specified_min_width.is_auto()) {
  305. if (used_width.to_px() < specified_min_width.to_px()) {
  306. used_width = try_compute_width(specified_min_width);
  307. }
  308. }
  309. rect().set_width(used_width.to_px());
  310. box_model().margin().left = margin_left;
  311. box_model().margin().right = margin_right;
  312. box_model().border().left = border_left;
  313. box_model().border().right = border_right;
  314. box_model().padding().left = padding_left;
  315. box_model().padding().right = padding_right;
  316. }
  317. void LayoutBlock::compute_position()
  318. {
  319. auto& style = this->style();
  320. auto auto_value = Length();
  321. auto zero_value = Length(0, Length::Type::Absolute);
  322. auto& containing_block = *this->containing_block();
  323. auto width = style.length_or_fallback(CSS::PropertyID::Width, auto_value, containing_block.width());
  324. if (style.position() == CSS::Position::Absolute) {
  325. box_model().offset().top = style.length_or_fallback(CSS::PropertyID::Top, zero_value, containing_block.height());
  326. box_model().offset().right = style.length_or_fallback(CSS::PropertyID::Right, zero_value, containing_block.width());
  327. box_model().offset().bottom = style.length_or_fallback(CSS::PropertyID::Bottom, zero_value, containing_block.height());
  328. box_model().offset().left = style.length_or_fallback(CSS::PropertyID::Left, zero_value, containing_block.width());
  329. }
  330. box_model().margin().top = style.length_or_fallback(CSS::PropertyID::MarginTop, zero_value, containing_block.width());
  331. box_model().margin().bottom = style.length_or_fallback(CSS::PropertyID::MarginBottom, zero_value, containing_block.width());
  332. box_model().border().top = style.length_or_fallback(CSS::PropertyID::BorderTopWidth, zero_value);
  333. box_model().border().bottom = style.length_or_fallback(CSS::PropertyID::BorderBottomWidth, zero_value);
  334. box_model().padding().top = style.length_or_fallback(CSS::PropertyID::PaddingTop, zero_value, containing_block.width());
  335. box_model().padding().bottom = style.length_or_fallback(CSS::PropertyID::PaddingBottom, zero_value, containing_block.width());
  336. float position_x = box_model().margin().left.to_px()
  337. + box_model().border().left.to_px()
  338. + box_model().padding().left.to_px()
  339. + box_model().offset().left.to_px();
  340. if (style.position() != CSS::Position::Absolute || containing_block.style().position() == CSS::Position::Absolute)
  341. position_x += containing_block.x();
  342. rect().set_x(position_x);
  343. float position_y = box_model().full_margin().top
  344. + box_model().offset().top.to_px();
  345. if (style.position() != CSS::Position::Absolute || containing_block.style().position() == CSS::Position::Absolute) {
  346. LayoutBlock* relevant_sibling = previous_sibling();
  347. while (relevant_sibling != nullptr) {
  348. if (relevant_sibling->style().position() != CSS::Position::Absolute)
  349. break;
  350. relevant_sibling = relevant_sibling->previous_sibling();
  351. }
  352. if (relevant_sibling == nullptr) {
  353. position_y += containing_block.y();
  354. } else {
  355. auto& previous_sibling_rect = relevant_sibling->rect();
  356. auto& previous_sibling_style = relevant_sibling->box_model();
  357. position_y += previous_sibling_rect.y() + previous_sibling_rect.height();
  358. position_y += previous_sibling_style.full_margin().bottom;
  359. }
  360. }
  361. rect().set_y(position_y);
  362. }
  363. void LayoutBlock::compute_height()
  364. {
  365. auto& style = this->style();
  366. auto height = style.length_or_fallback(CSS::PropertyID::Height, Length(), containing_block()->height());
  367. if (height.is_absolute())
  368. rect().set_height(height.to_px());
  369. }
  370. void LayoutBlock::render(RenderingContext& context)
  371. {
  372. if (!is_visible())
  373. return;
  374. LayoutBox::render(context);
  375. if (children_are_inline()) {
  376. for (auto& line_box : m_line_boxes) {
  377. for (auto& fragment : line_box.fragments()) {
  378. if (context.should_show_line_box_borders())
  379. context.painter().draw_rect(enclosing_int_rect(fragment.rect()), Color::Green);
  380. fragment.render(context);
  381. }
  382. }
  383. }
  384. }
  385. HitTestResult LayoutBlock::hit_test(const Gfx::Point& position) const
  386. {
  387. if (!children_are_inline())
  388. return LayoutBox::hit_test(position);
  389. HitTestResult result;
  390. for (auto& line_box : m_line_boxes) {
  391. for (auto& fragment : line_box.fragments()) {
  392. if (enclosing_int_rect(fragment.rect()).contains(position)) {
  393. if (fragment.layout_node().is_block())
  394. return to<LayoutBlock>(fragment.layout_node()).hit_test(position);
  395. return { fragment.layout_node(), fragment.text_index_at(position.x()) };
  396. }
  397. }
  398. }
  399. // FIXME: This should be smarter about the text position if we're hitting a block
  400. // that has text inside it, but `position` is to the right of the text box.
  401. return { rect().contains(position.x(), position.y()) ? this : nullptr };
  402. }
  403. NonnullRefPtr<StyleProperties> LayoutBlock::style_for_anonymous_block() const
  404. {
  405. auto new_style = StyleProperties::create();
  406. style().for_each_property([&](auto property_id, auto& value) {
  407. if (StyleResolver::is_inherited_property(property_id))
  408. new_style->set_property(property_id, value);
  409. });
  410. return new_style;
  411. }
  412. LineBox& LayoutBlock::ensure_last_line_box()
  413. {
  414. if (m_line_boxes.is_empty())
  415. m_line_boxes.append(LineBox());
  416. return m_line_boxes.last();
  417. }
  418. LineBox& LayoutBlock::add_line_box()
  419. {
  420. m_line_boxes.append(LineBox());
  421. return m_line_boxes.last();
  422. }
  423. void LayoutBlock::split_into_lines(LayoutBlock& container, LayoutMode layout_mode)
  424. {
  425. ASSERT(is_inline());
  426. layout(layout_mode);
  427. auto* line_box = &container.ensure_last_line_box();
  428. if (line_box->width() > 0 && line_box->width() + width() > container.width())
  429. line_box = &container.add_line_box();
  430. line_box->add_fragment(*this, 0, 0, width(), height());
  431. }
  432. }