Icon.cpp 2.4 KB

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