summaryrefslogtreecommitdiff
path: root/Libraries/LibHTML/HtmlView.cpp
blob: dec45d1fef8b9390b6204c89849c60078cbbc047 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#include <AK/FileSystemPath.h>
#include <LibCore/CFile.h>
#include <LibDraw/PNGLoader.h>
#include <LibGUI/GApplication.h>
#include <LibGUI/GPainter.h>
#include <LibGUI/GScrollBar.h>
#include <LibGUI/GWindow.h>
#include <LibHTML/DOM/Element.h>
#include <LibHTML/DOM/ElementFactory.h>
#include <LibHTML/DOM/HTMLAnchorElement.h>
#include <LibHTML/DOM/HTMLImageElement.h>
#include <LibHTML/DOM/Text.h>
#include <LibHTML/Dump.h>
#include <LibHTML/Frame.h>
#include <LibHTML/HtmlView.h>
#include <LibHTML/Layout/LayoutDocument.h>
#include <LibHTML/Layout/LayoutNode.h>
#include <LibHTML/Parser/HTMLParser.h>
#include <LibHTML/RenderingContext.h>
#include <LibHTML/ResourceLoader.h>
#include <stdio.h>

HtmlView::HtmlView(GWidget* parent)
    : GScrollableWidget(parent)
    , m_main_frame(Frame::create(*this))
{
    main_frame().on_set_needs_display = [this](auto& content_rect) {
        if (content_rect.is_empty()) {
            update();
            return;
        }
        Rect adjusted_rect = content_rect;
        adjusted_rect.set_location(to_widget_position(content_rect.location()));
        update(adjusted_rect);
    };

    set_frame_shape(FrameShape::Container);
    set_frame_shadow(FrameShadow::Sunken);
    set_frame_thickness(2);
    set_should_hide_unnecessary_scrollbars(true);
    set_background_color(Color::White);
}

HtmlView::~HtmlView()
{
}

void HtmlView::set_document(Document* new_document)
{
    RefPtr<Document> old_document = document();

    if (new_document == old_document)
        return;

    if (old_document)
        old_document->on_layout_updated = nullptr;

    main_frame().set_document(new_document);

    if (new_document) {
        new_document->on_layout_updated = [this] {
            layout_and_sync_size();
            update();
        };
    }

#ifdef HTML_DEBUG
    if (document != nullptr) {
        dbgprintf("\033[33;1mLayout tree before layout:\033[0m\n");
        ::dump_tree(*layout_root());
    }
#endif

    layout_and_sync_size();
    update();
}

void HtmlView::layout_and_sync_size()
{
    if (!document())
        return;

    bool had_vertical_scrollbar = vertical_scrollbar().is_visible();
    bool had_horizontal_scrollbar = horizontal_scrollbar().is_visible();

    main_frame().set_size(available_size());
    document()->layout();
    set_content_size(enclosing_int_rect(layout_root()->rect()).size());

    // NOTE: If layout caused us to gain or lose scrollbars, we have to lay out again
    //       since the scrollbars now take up some of the available space.
    if (had_vertical_scrollbar != vertical_scrollbar().is_visible() || had_horizontal_scrollbar != horizontal_scrollbar().is_visible()) {
        main_frame().set_size(available_size());
        document()->layout();
        set_content_size(enclosing_int_rect(layout_root()->rect()).size());
    }

#ifdef HTML_DEBUG
    dbgprintf("\033[33;1mLayout tree after layout:\033[0m\n");
    ::dump_tree(*layout_root());
#endif
}

void HtmlView::resize_event(GResizeEvent& event)
{
    GScrollableWidget::resize_event(event);
    layout_and_sync_size();
}

void HtmlView::paint_event(GPaintEvent& event)
{
    GFrame::paint_event(event);

    GPainter painter(*this);
    painter.add_clip_rect(widget_inner_rect());
    painter.add_clip_rect(event.rect());

    if (!layout_root()) {
        painter.fill_rect(event.rect(), background_color());
        return;
    }

    painter.fill_rect(event.rect(), document()->background_color());

    if (auto background_bitmap = document()->background_image()) {
        painter.draw_tiled_bitmap(event.rect(), *background_bitmap);
    }

    painter.translate(frame_thickness(), frame_thickness());
    painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());

    RenderingContext context { painter };
    context.set_should_show_line_box_borders(m_should_show_line_box_borders);
    context.set_viewport_rect(visible_content_rect());
    layout_root()->render(context);
}

void HtmlView::mousemove_event(GMouseEvent& event)
{
    if (!layout_root())
        return GScrollableWidget::mousemove_event(event);

    bool hovered_node_changed = false;
    bool is_hovering_link = false;
    bool was_hovering_link = document()->hovered_node() && document()->hovered_node()->is_link();
    auto result = layout_root()->hit_test(to_content_position(event.position()));
    const HTMLAnchorElement* hovered_link_element = nullptr;
    if (result.layout_node) {
        auto* node = result.layout_node->node();
        hovered_node_changed = node != document()->hovered_node();
        document()->set_hovered_node(const_cast<Node*>(node));
        if (node) {
            hovered_link_element = node->enclosing_link_element();
            if (hovered_link_element) {
#ifdef HTML_DEBUG
                dbg() << "HtmlView: hovering over a link to " << hovered_link_element->href();
#endif
                is_hovering_link = true;
            }
        }
        if (m_in_mouse_selection) {
            layout_root()->selection().set_end({ result.layout_node, result.index_in_node });
            dump_selection("MouseMove");
            update();
        }
    }
    if (window())
        window()->set_override_cursor(is_hovering_link ? GStandardCursor::Hand : GStandardCursor::None);
    if (hovered_node_changed) {
        update();
        auto* hovered_html_element = document()->hovered_node() ? document()->hovered_node()->enclosing_html_element() : nullptr;
        if (hovered_html_element && !hovered_html_element->title().is_null()) {
            auto screen_position = screen_relative_rect().location().translated(event.position());
            GApplication::the().show_tooltip(hovered_html_element->title(), screen_position.translated(4, 4));
        } else {
            GApplication::the().hide_tooltip();
        }
    }
    if (is_hovering_link != was_hovering_link) {
        if (on_link_hover) {
            on_link_hover(hovered_link_element ? document()->complete_url(hovered_link_element->href()).to_string() : String());
        }
    }
    event.accept();
}

void HtmlView::mousedown_event(GMouseEvent& event)
{
    if (!layout_root())
        return GScrollableWidget::mousemove_event(event);

    bool hovered_node_changed = false;
    auto result = layout_root()->hit_test(to_content_position(event.position()));
    if (result.layout_node) {
        auto* node = result.layout_node->node();
        hovered_node_changed = node != document()->hovered_node();
        document()->set_hovered_node(const_cast<Node*>(node));
        if (node) {
            if (auto* link = node->enclosing_link_element()) {
                dbg() << "HtmlView: clicking on a link to " << link->href();
                if (on_link_click)
                    on_link_click(link->href());
            } else {
                if (event.button() == GMouseButton::Left) {
                    layout_root()->selection().set({ result.layout_node, result.index_in_node }, {});
                    dump_selection("MouseDown");
                    m_in_mouse_selection = true;
                }
            }
        }
    }
    if (hovered_node_changed)
        update();
    event.accept();
}

void HtmlView::mouseup_event(GMouseEvent& event)
{
    if (!layout_root())
        return GScrollableWidget::mouseup_event(event);

    if (event.button() == GMouseButton::Left) {
        dump_selection("MouseUp");
        m_in_mouse_selection = false;
    }
}

void HtmlView::keydown_event(GKeyEvent& event)
{
    if (event.modifiers() == 0) {
        switch (event.key()) {
        case Key_Home:
            vertical_scrollbar().set_value(0);
            break;
        case Key_End:
            vertical_scrollbar().set_value(vertical_scrollbar().max());
            break;
        case Key_Down:
            vertical_scrollbar().set_value(vertical_scrollbar().value() + vertical_scrollbar().step());
            break;
        case Key_Up:
            vertical_scrollbar().set_value(vertical_scrollbar().value() - vertical_scrollbar().step());
            break;
        case Key_Left:
            horizontal_scrollbar().set_value(horizontal_scrollbar().value() + horizontal_scrollbar().step());
            break;
        case Key_Right:
            horizontal_scrollbar().set_value(horizontal_scrollbar().value() - horizontal_scrollbar().step());
            break;
        case Key_PageDown:
            vertical_scrollbar().set_value(vertical_scrollbar().value() + frame_inner_rect().height());
            break;
        case Key_PageUp:
            vertical_scrollbar().set_value(vertical_scrollbar().value() - frame_inner_rect().height());
            break;
        }
    }

    event.accept();
}

void HtmlView::reload()
{
    load(main_frame().document()->url());
}

static RefPtr<Document> create_image_document(const ByteBuffer& data, const URL& url)
{
    auto document = adopt(*new Document);
    document->set_url(url);

    auto bitmap = load_png_from_memory(data.data(), data.size());
    ASSERT(bitmap);

    auto html_element = create_element(document, "html");
    document->append_child(html_element);

    auto head_element = create_element(document, "head");
    html_element->append_child(head_element);
    auto title_element = create_element(document, "title");
    head_element->append_child(title_element);

    auto basename = FileSystemPath(url.path()).basename();
    auto title_text = adopt(*new Text(document, String::format("%s [%dx%d]", basename.characters(), bitmap->width(), bitmap->height())));
    title_element->append_child(title_text);

    auto body_element = create_element(document, "body");
    html_element->append_child(body_element);

    auto image_element = create_element(document, "img");
    image_element->set_attribute("src", url.to_string());
    body_element->append_child(image_element);

    return document;
}

void HtmlView::load(const URL& url)
{
    dbg() << "HtmlView::load: " << url;

    if (window())
        window()->set_override_cursor(GStandardCursor::None);

    if (on_load_start)
        on_load_start(url);

    ResourceLoader::the().load(url, [=](auto data) {
        if (data.is_null()) {
            dbg() << "Load failed!";
            ASSERT_NOT_REACHED();
        }

        RefPtr<Document> document;
        if (url.path().ends_with(".png")) {
            document = create_image_document(data, url);
        } else {
            document = parse_html_document(data, url);
        }
        ASSERT(document);
        set_document(document);
        if (on_title_change)
            on_title_change(document->title());
    });
}

const LayoutDocument* HtmlView::layout_root() const
{
    return document() ? document()->layout_node() : nullptr;
}

LayoutDocument* HtmlView::layout_root()
{
    if (!document())
        return nullptr;
    return const_cast<LayoutDocument*>(document()->layout_node());
}

void HtmlView::scroll_to_anchor(const StringView& name)
{
    if (!document())
        return;

    auto* element = document()->get_element_by_id(name);
    if (!element) {
        auto candidates = document()->get_elements_by_name(name);
        for (auto* candidate : candidates) {
            if (is<HTMLAnchorElement>(*candidate)) {
                element = to<HTMLAnchorElement>(candidate);
                break;
            }
        }
    }

    if (!element) {
        dbg() << "HtmlView::scroll_to_anchor(): Anchor not found: '" << name << "'";
        return;
    }
    if (!element->layout_node()) {
        dbg() << "HtmlView::scroll_to_anchor(): Anchor found but without layout node: '" << name << "'";
        return;
    }
    auto& layout_node = *element->layout_node();
    FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)visible_content_rect().width(), (float)visible_content_rect().height() } };
    scroll_into_view(enclosing_int_rect(float_rect), true, true);
    window()->set_override_cursor(GStandardCursor::None);
}

Document* HtmlView::document()
{
    return main_frame().document();
}

const Document* HtmlView::document() const
{
    return main_frame().document();
}

void HtmlView::dump_selection(const char* event_name)
{
    dbg() << event_name << " selection start: "
          << layout_root()->selection().start().layout_node << ":" << layout_root()->selection().start().index_in_node << ", end: "
          << layout_root()->selection().end().layout_node << ":" << layout_root()->selection().end().index_in_node;
}