summaryrefslogtreecommitdiff
path: root/LibGUI/GIcon.cpp
blob: 17c34e835616aa63fd8a976b8c2ce264ecd951c6 (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
#include <LibGUI/GIcon.h>

GIcon::GIcon()
    : m_impl(GIconImpl::create())
{
}

GIcon::GIcon(const GIconImpl& impl)
    : m_impl(const_cast<GIconImpl&>(impl))
{
}

GIcon::GIcon(const GIcon& other)
    : m_impl(other.m_impl.copy_ref())
{
}

GIcon::GIcon(RetainPtr<GraphicsBitmap>&& bitmap)
    : GIcon()
{
    if (bitmap) {
        ASSERT(bitmap->width() == bitmap->height());
        int size = bitmap->width();
        set_bitmap_for_size(size, move(bitmap));
    }
}

GIcon::GIcon(RetainPtr<GraphicsBitmap>&& bitmap1, RetainPtr<GraphicsBitmap>&& bitmap2)
    : GIcon(move(bitmap1))
{
    if (bitmap2) {
        ASSERT(bitmap2->width() == bitmap2->height());
        int size = bitmap2->width();
        set_bitmap_for_size(size, move(bitmap2));
    }
}

const GraphicsBitmap* GIconImpl::bitmap_for_size(int size) const
{
    auto it = m_bitmaps.find(size);
    if (it != m_bitmaps.end())
        return it->value.ptr();

    int best_diff_so_far = INT32_MAX;
    const GraphicsBitmap* best_fit = nullptr;
    for (auto& it : m_bitmaps) {
        int abs_diff = abs(it.key - size);
        if (abs_diff < best_diff_so_far) {
            best_diff_so_far = abs_diff;
            best_fit = it.value.ptr();
        }
    }
    return best_fit;
}

void GIconImpl::set_bitmap_for_size(int size, RetainPtr<GraphicsBitmap>&& bitmap)
{
    if (!bitmap) {
        m_bitmaps.remove(size);
        return;
    }
    m_bitmaps.set(size, move(bitmap));
}

GIcon GIcon::default_icon(const StringView& name)
{
    auto bitmap16 = GraphicsBitmap::load_from_file(String::format("/res/icons/16x16/%s.png", name.characters()));
    auto bitmap32 = GraphicsBitmap::load_from_file(String::format("/res/icons/32x32/%s.png", name.characters()));
    return GIcon(move(bitmap16), move(bitmap32));
}