Icon.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibGUI/Icon.h>
  8. #include <LibGfx/Bitmap.h>
  9. namespace GUI {
  10. Icon::Icon()
  11. : m_impl(IconImpl::create())
  12. {
  13. }
  14. Icon::Icon(const IconImpl& impl)
  15. : m_impl(const_cast<IconImpl&>(impl))
  16. {
  17. }
  18. Icon::Icon(const Icon& other)
  19. : m_impl(other.m_impl)
  20. {
  21. }
  22. Icon::Icon(RefPtr<Gfx::Bitmap>&& bitmap)
  23. : Icon()
  24. {
  25. if (bitmap) {
  26. VERIFY(bitmap->width() == bitmap->height());
  27. int size = bitmap->width();
  28. set_bitmap_for_size(size, move(bitmap));
  29. }
  30. }
  31. Icon::Icon(RefPtr<Gfx::Bitmap>&& bitmap1, RefPtr<Gfx::Bitmap>&& bitmap2)
  32. : Icon(move(bitmap1))
  33. {
  34. if (bitmap2) {
  35. VERIFY(bitmap2->width() == bitmap2->height());
  36. int size = bitmap2->width();
  37. set_bitmap_for_size(size, move(bitmap2));
  38. }
  39. }
  40. const Gfx::Bitmap* IconImpl::bitmap_for_size(int size) const
  41. {
  42. auto it = m_bitmaps.find(size);
  43. if (it != m_bitmaps.end())
  44. return it->value.ptr();
  45. int best_diff_so_far = INT32_MAX;
  46. const Gfx::Bitmap* best_fit = nullptr;
  47. for (auto& it : m_bitmaps) {
  48. int abs_diff = abs(it.key - size);
  49. if (abs_diff < best_diff_so_far) {
  50. best_diff_so_far = abs_diff;
  51. best_fit = it.value.ptr();
  52. }
  53. }
  54. return best_fit;
  55. }
  56. void IconImpl::set_bitmap_for_size(int size, RefPtr<Gfx::Bitmap>&& bitmap)
  57. {
  58. if (!bitmap) {
  59. m_bitmaps.remove(size);
  60. return;
  61. }
  62. m_bitmaps.set(size, move(bitmap));
  63. }
  64. Icon Icon::default_icon(const StringView& name)
  65. {
  66. RefPtr<Gfx::Bitmap> bitmap16;
  67. RefPtr<Gfx::Bitmap> bitmap32;
  68. if (auto bitmap_or_error = Gfx::Bitmap::try_load_from_file(String::formatted("/res/icons/16x16/{}.png", name)); !bitmap_or_error.is_error())
  69. bitmap16 = bitmap_or_error.release_value();
  70. if (auto bitmap_or_error = Gfx::Bitmap::try_load_from_file(String::formatted("/res/icons/32x32/{}.png", name)); !bitmap_or_error.is_error())
  71. bitmap32 = bitmap_or_error.release_value();
  72. return Icon(move(bitmap16), move(bitmap32));
  73. }
  74. }