summaryrefslogtreecommitdiff
path: root/Ladybird/LocationEdit.cpp
blob: e2368444c433044c55c2f5957e47731b68a7686c (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
/*
 * Copyright (c) 2023, Cameron Youell <cameronyouell@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "LocationEdit.h"
#include "Utilities.h"
#include <AK/URL.h>
#include <QCoreApplication>
#include <QPalette>
#include <QTextLayout>

LocationEdit::LocationEdit(QWidget* parent)
    : QLineEdit(parent)
{
    connect(this, &QLineEdit::returnPressed, this, [&] {
        clearFocus();
    });

    connect(this, &QLineEdit::textChanged, this, [&] {
        highlight_location();
    });
}

void LocationEdit::focusInEvent(QFocusEvent* event)
{
    QLineEdit::focusInEvent(event);
    highlight_location();
}

void LocationEdit::focusOutEvent(QFocusEvent* event)
{
    QLineEdit::focusOutEvent(event);
    highlight_location();
}

void LocationEdit::highlight_location()
{
    auto url = AK::URL::create_with_url_or_path(ak_deprecated_string_from_qstring(text()));

    auto darkened_text_color = QPalette().color(QPalette::Text);
    darkened_text_color.setAlpha(127);

    QList<QInputMethodEvent::Attribute> attributes;
    if (url.is_valid() && !hasFocus()) {
        if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "gemini") {
            int host_start = (url.scheme().length() + 3) - cursorPosition();
            auto host_length = url.host().length();

            // FIXME: Maybe add a generator to use https://publicsuffix.org/list/public_suffix_list.dat
            //        for now just highlight the whole host

            QTextCharFormat defaultFormat;
            defaultFormat.setForeground(darkened_text_color);
            attributes.append({
                QInputMethodEvent::TextFormat,
                -cursorPosition(),
                static_cast<int>(text().length()),
                defaultFormat,
            });

            QTextCharFormat hostFormat;
            hostFormat.setForeground(QPalette().color(QPalette::Text));
            attributes.append({
                QInputMethodEvent::TextFormat,
                host_start,
                static_cast<int>(host_length),
                hostFormat,
            });
        } else if (url.scheme() == "file") {
            QTextCharFormat schemeFormat;
            schemeFormat.setForeground(darkened_text_color);
            attributes.append({
                QInputMethodEvent::TextFormat,
                -cursorPosition(),
                static_cast<int>(url.scheme().length() + 3),
                schemeFormat,
            });
        }
    }

    QInputMethodEvent event(QString(), attributes);
    QCoreApplication::sendEvent(this, &event);
}