Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2022, Filiph Sandström <filiph.sandstrom@filfatstudios.com>
4 * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 */
8
9#include <AK/JsonValue.h>
10#include <AK/NonnullRefPtr.h>
11#include <LibGUI/Icon.h>
12#include <LibGUI/Variant.h>
13
14namespace GUI {
15
16Variant::Variant(JsonValue const& value)
17{
18 *this = value;
19}
20
21Variant& Variant::operator=(JsonValue const& value)
22{
23 if (value.is_null())
24 return *this;
25
26 if (value.is_i32()) {
27 set(value.as_i32());
28 return *this;
29 }
30
31 if (value.is_u32()) {
32 set(value.as_u32());
33 return *this;
34 }
35
36 if (value.is_i64()) {
37 set(value.as_i64());
38 return *this;
39 }
40
41 if (value.is_u64()) {
42 set(value.as_u64());
43 return *this;
44 }
45
46 if (value.is_string()) {
47 set(value.as_string());
48 return *this;
49 }
50
51 if (value.is_bool()) {
52 set(Detail::Boolean { value.as_bool() });
53 return *this;
54 }
55
56 VERIFY_NOT_REACHED();
57}
58
59bool Variant::operator==(Variant const& other) const
60{
61 return visit([&]<typename T>(T const& own_value) {
62 return other.visit(
63 [&](T const& other_value) -> bool {
64 if constexpr (requires { own_value == other_value; })
65 return own_value == other_value;
66 else if constexpr (IsSame<T, GUI::Icon>)
67 return &own_value.impl() == &other_value.impl();
68 // FIXME: Figure out if this silly behaviour is actually used anywhere, then get rid of it.
69 else
70 return to_deprecated_string() == other.to_deprecated_string();
71 },
72 [&](auto const&) {
73 // FIXME: Figure out if this silly behaviour is actually used anywhere, then get rid of it.
74 return to_deprecated_string() == other.to_deprecated_string();
75 });
76 });
77}
78
79bool Variant::operator<(Variant const& other) const
80{
81 return visit([&]<typename T>(T const& own_value) {
82 return other.visit(
83 [&](T const& other_value) -> bool {
84 // FIXME: Maybe compare icons somehow differently?
85 if constexpr (IsSame<T, GUI::Icon>)
86 return &own_value.impl() < &other_value.impl();
87 // FIXME: Maybe compare bitmaps somehow differently?
88 else if constexpr (IsSame<T, NonnullRefPtr<Gfx::Bitmap>>)
89 return own_value.ptr() < other_value.ptr();
90 else if constexpr (IsSame<T, NonnullRefPtr<Gfx::Font>>)
91 return own_value->name() < other_value->name();
92 else if constexpr (requires { own_value < other_value; })
93 return own_value < other_value;
94 // FIXME: Figure out if this silly behaviour is actually used anywhere, then get rid of it.
95 else
96 return to_deprecated_string() < other.to_deprecated_string();
97 },
98 [&](auto const&) -> bool {
99 return to_deprecated_string() < other.to_deprecated_string(); // FIXME: Figure out if this silly behaviour is actually used anywhere, then get rid of it.
100 });
101 });
102}
103}