summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/CSS/Angle.cpp
blob: f1d1d4357d0bf628157e6c0602b0e45c41a10e49 (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
/*
 * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Angle.h"
#include <AK/Math.h>
#include <LibWeb/CSS/StyleValue.h>

namespace Web::CSS {

Angle::Angle(int value, Type type)
    : m_type(type)
    , m_value(value)
{
}

Angle::Angle(float value, Type type)
    : m_type(type)
    , m_value(value)
{
}

Angle Angle::make_calculated(NonnullRefPtr<CalculatedStyleValue> calculated_style_value)
{
    Angle angle { 0, Type::Calculated };
    angle.m_calculated_style = move(calculated_style_value);
    return angle;
}

Angle Angle::make_degrees(float value)
{
    return { value, Type::Deg };
}

Angle Angle::percentage_of(Percentage const& percentage) const
{
    VERIFY(!is_calculated());

    return Angle { percentage.as_fraction() * m_value, m_type };
}

ErrorOr<String> Angle::to_string() const
{
    if (is_calculated())
        return m_calculated_style->to_string();
    return String::formatted("{}{}", m_value, unit_name());
}

float Angle::to_degrees() const
{
    switch (m_type) {
    case Type::Calculated:
        return m_calculated_style->resolve_angle()->to_degrees();
    case Type::Deg:
        return m_value;
    case Type::Grad:
        return m_value * (360.0f / 400.0f);
    case Type::Rad:
        return m_value * (180.0f / AK::Pi<float>);
    case Type::Turn:
        return m_value * 360.0f;
    }
    VERIFY_NOT_REACHED();
}

StringView Angle::unit_name() const
{
    switch (m_type) {
    case Type::Calculated:
        return "calculated"sv;
    case Type::Deg:
        return "deg"sv;
    case Type::Grad:
        return "grad"sv;
    case Type::Rad:
        return "rad"sv;
    case Type::Turn:
        return "turn"sv;
    }
    VERIFY_NOT_REACHED();
}

Optional<Angle::Type> Angle::unit_from_name(StringView name)
{
    if (name.equals_ignoring_case("deg"sv)) {
        return Type::Deg;
    } else if (name.equals_ignoring_case("grad"sv)) {
        return Type::Grad;
    } else if (name.equals_ignoring_case("rad"sv)) {
        return Type::Rad;
    } else if (name.equals_ignoring_case("turn"sv)) {
        return Type::Turn;
    }
    return {};
}

NonnullRefPtr<CalculatedStyleValue> Angle::calculated_style_value() const
{
    VERIFY(!m_calculated_style.is_null());
    return *m_calculated_style;
}

}