Serenity Operating System
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
27#include <AK/Utf8View.h>
28#include <LibGUI/Painter.h>
29#include <LibHTML/Layout/LayoutDocument.h>
30#include <LibHTML/Layout/LayoutText.h>
31#include <LibHTML/Layout/LineBoxFragment.h>
32#include <LibHTML/RenderingContext.h>
33
34void LineBoxFragment::render(RenderingContext& context)
35{
36 for (auto* ancestor = layout_node().parent(); ancestor; ancestor = ancestor->parent()) {
37 if (!ancestor->is_visible())
38 return;
39 }
40
41 if (is<LayoutText>(layout_node())) {
42 to<LayoutText>(layout_node()).render_fragment(context, *this);
43 }
44}
45
46bool LineBoxFragment::is_justifiable_whitespace() const
47{
48 return text() == " ";
49}
50
51StringView LineBoxFragment::text() const
52{
53 if (!is<LayoutText>(layout_node()))
54 return {};
55 return to<LayoutText>(layout_node()).text_for_rendering().substring_view(m_start, m_length);
56}
57
58int LineBoxFragment::text_index_at(float x) const
59{
60 if (!layout_node().is_text())
61 return 0;
62 auto& layout_text = to<LayoutText>(layout_node());
63 auto& font = layout_text.style().font();
64 Utf8View view(text());
65
66 float relative_x = x - m_rect.location().x();
67 float glyph_spacing = font.glyph_spacing();
68
69 float width_so_far = 0;
70 for (auto it = view.begin(); it != view.end(); ++it) {
71 float glyph_width = font.glyph_or_emoji_width(*it);
72 if ((width_so_far + glyph_width + glyph_spacing) > relative_x)
73 return m_start + view.byte_offset_of(it);
74 width_so_far += glyph_width + glyph_spacing;
75 }
76 return m_start + m_length - 1;
77}