ladybird/LibGUI/GIcon.cpp
Andreas Kling be604652ae LibGUI: Add GIcon::default_icon(name).
This is a convenience helper to instantiate a GIcon like so:

    auto icon = GIcon::default_icon("filetype-image");

This will give you the "filetype-image" icon in both 16x16 and 32x32 sizes.
2019-03-25 14:46:37 +01:00

70 lines
1.7 KiB
C++

#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 String& 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));
}