Bitmap.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/Memory.h>
  9. #include <AK/MemoryStream.h>
  10. #include <AK/Optional.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/String.h>
  13. #include <AK/Try.h>
  14. #include <LibCore/MappedFile.h>
  15. #include <LibCore/System.h>
  16. #include <LibGfx/Bitmap.h>
  17. #include <LibGfx/ImageDecoder.h>
  18. #include <LibGfx/ShareableBitmap.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <stdio.h>
  22. #include <sys/mman.h>
  23. namespace Gfx {
  24. struct BackingStore {
  25. void* data { nullptr };
  26. size_t pitch { 0 };
  27. size_t size_in_bytes { 0 };
  28. };
  29. size_t Bitmap::minimum_pitch(size_t physical_width, BitmapFormat format)
  30. {
  31. size_t element_size;
  32. switch (determine_storage_format(format)) {
  33. case StorageFormat::Indexed8:
  34. element_size = 1;
  35. break;
  36. case StorageFormat::BGRx8888:
  37. case StorageFormat::BGRA8888:
  38. case StorageFormat::RGBA8888:
  39. element_size = 4;
  40. break;
  41. default:
  42. VERIFY_NOT_REACHED();
  43. }
  44. return physical_width * element_size;
  45. }
  46. static bool size_would_overflow(BitmapFormat format, IntSize const& size, int scale_factor)
  47. {
  48. if (size.width() < 0 || size.height() < 0)
  49. return true;
  50. // This check is a bit arbitrary, but should protect us from most shenanigans:
  51. if (size.width() >= INT16_MAX || size.height() >= INT16_MAX || scale_factor < 1 || scale_factor > 4)
  52. return true;
  53. // In contrast, this check is absolutely necessary:
  54. size_t pitch = Bitmap::minimum_pitch(size.width() * scale_factor, format);
  55. return Checked<size_t>::multiplication_would_overflow(pitch, size.height() * scale_factor);
  56. }
  57. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create(BitmapFormat format, IntSize const& size, int scale_factor)
  58. {
  59. auto backing_store = TRY(Bitmap::allocate_backing_store(format, size, scale_factor));
  60. return AK::adopt_nonnull_ref_or_enomem(new (nothrow) Bitmap(format, size, scale_factor, backing_store));
  61. }
  62. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_shareable(BitmapFormat format, IntSize const& size, int scale_factor)
  63. {
  64. if (size_would_overflow(format, size, scale_factor))
  65. return Error::from_string_literal("Gfx::Bitmap::try_create_shareable size overflow"sv);
  66. auto const pitch = minimum_pitch(size.width() * scale_factor, format);
  67. auto const data_size = size_in_bytes(pitch, size.height() * scale_factor);
  68. auto buffer = TRY(Core::AnonymousBuffer::create_with_size(round_up_to_power_of_two(data_size, PAGE_SIZE)));
  69. auto bitmap = TRY(Bitmap::try_create_with_anonymous_buffer(format, buffer, size, scale_factor, {}));
  70. return bitmap;
  71. }
  72. Bitmap::Bitmap(BitmapFormat format, IntSize const& size, int scale_factor, BackingStore const& backing_store)
  73. : m_size(size)
  74. , m_scale(scale_factor)
  75. , m_data(backing_store.data)
  76. , m_pitch(backing_store.pitch)
  77. , m_format(format)
  78. {
  79. VERIFY(!m_size.is_empty());
  80. VERIFY(!size_would_overflow(format, size, scale_factor));
  81. VERIFY(m_data);
  82. VERIFY(backing_store.size_in_bytes == size_in_bytes());
  83. allocate_palette_from_format(format, {});
  84. m_needs_munmap = true;
  85. }
  86. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_wrapper(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data)
  87. {
  88. if (size_would_overflow(format, size, scale_factor))
  89. return Error::from_string_literal("Gfx::Bitmap::try_create_wrapper size overflow"sv);
  90. return adopt_ref(*new Bitmap(format, size, scale_factor, pitch, data));
  91. }
  92. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_load_from_file(String const& path, int scale_factor)
  93. {
  94. if (scale_factor > 1 && path.starts_with("/res/")) {
  95. LexicalPath lexical_path { path };
  96. StringBuilder highdpi_icon_path;
  97. highdpi_icon_path.append(lexical_path.dirname());
  98. highdpi_icon_path.append('/');
  99. highdpi_icon_path.append(lexical_path.title());
  100. highdpi_icon_path.appendff("-{}x.", scale_factor);
  101. highdpi_icon_path.append(lexical_path.extension());
  102. auto highdpi_icon_string = highdpi_icon_path.to_string();
  103. auto fd = TRY(Core::System::open(highdpi_icon_string, O_RDONLY));
  104. auto bitmap = TRY(try_load_from_fd_and_close(fd, highdpi_icon_string));
  105. if (bitmap->width() % scale_factor != 0 || bitmap->height() % scale_factor != 0)
  106. return Error::from_string_literal("Bitmap::try_load_from_file: HighDPI image size should be divisible by scale factor");
  107. bitmap->m_size.set_width(bitmap->width() / scale_factor);
  108. bitmap->m_size.set_height(bitmap->height() / scale_factor);
  109. bitmap->m_scale = scale_factor;
  110. return bitmap;
  111. }
  112. auto fd = TRY(Core::System::open(path, O_RDONLY));
  113. return try_load_from_fd_and_close(fd, path);
  114. }
  115. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_load_from_fd_and_close(int fd, String const& path)
  116. {
  117. auto file = TRY(Core::MappedFile::map_from_fd_and_close(fd, path));
  118. if (auto decoder = ImageDecoder::try_create(file->bytes())) {
  119. auto frame = TRY(decoder->frame(0));
  120. if (auto& bitmap = frame.image)
  121. return bitmap.release_nonnull();
  122. }
  123. return Error::from_string_literal("Gfx::Bitmap unable to load from fd"sv);
  124. }
  125. Bitmap::Bitmap(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data)
  126. : m_size(size)
  127. , m_scale(scale_factor)
  128. , m_data(data)
  129. , m_pitch(pitch)
  130. , m_format(format)
  131. {
  132. VERIFY(pitch >= minimum_pitch(size.width() * scale_factor, format));
  133. VERIFY(!size_would_overflow(format, size, scale_factor));
  134. // FIXME: assert that `data` is actually long enough!
  135. allocate_palette_from_format(format, {});
  136. }
  137. static bool check_size(IntSize const& size, int scale_factor, BitmapFormat format, unsigned actual_size)
  138. {
  139. // FIXME: Code duplication of size_in_bytes() and m_pitch
  140. unsigned expected_size_min = Bitmap::minimum_pitch(size.width() * scale_factor, format) * size.height() * scale_factor;
  141. unsigned expected_size_max = round_up_to_power_of_two(expected_size_min, PAGE_SIZE);
  142. if (expected_size_min > actual_size || actual_size > expected_size_max) {
  143. // Getting here is most likely an error.
  144. dbgln("Constructing a shared bitmap for format {} and size {} @ {}x, which demands {} bytes, which rounds up to at most {}.",
  145. static_cast<int>(format),
  146. size,
  147. scale_factor,
  148. expected_size_min,
  149. expected_size_max);
  150. dbgln("However, we were given {} bytes, which is outside this range?! Refusing cowardly.", actual_size);
  151. return false;
  152. }
  153. return true;
  154. }
  155. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_with_anonymous_buffer(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize const& size, int scale_factor, Vector<ARGB32> const& palette)
  156. {
  157. if (size_would_overflow(format, size, scale_factor))
  158. return Error::from_string_literal("Gfx::Bitmap::try_create_with_anonymous_buffer size overflow");
  159. return adopt_nonnull_ref_or_enomem(new (nothrow) Bitmap(format, move(buffer), size, scale_factor, palette));
  160. }
  161. /// Read a bitmap as described by:
  162. /// - actual size
  163. /// - width
  164. /// - height
  165. /// - scale_factor
  166. /// - format
  167. /// - palette count
  168. /// - palette data (= palette count * BGRA8888)
  169. /// - image data (= actual size * u8)
  170. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_from_serialized_byte_buffer(ByteBuffer&& buffer)
  171. {
  172. InputMemoryStream stream { buffer };
  173. size_t actual_size;
  174. unsigned width;
  175. unsigned height;
  176. unsigned scale_factor;
  177. BitmapFormat format;
  178. unsigned palette_size;
  179. Vector<ARGB32> palette;
  180. auto read = [&]<typename T>(T& value) {
  181. if (stream.read({ &value, sizeof(T) }) != sizeof(T))
  182. return false;
  183. return true;
  184. };
  185. if (!read(actual_size) || !read(width) || !read(height) || !read(scale_factor) || !read(format) || !read(palette_size))
  186. return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv);
  187. if (format > BitmapFormat::BGRA8888 || format < BitmapFormat::Indexed1)
  188. return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv);
  189. if (!check_size({ width, height }, scale_factor, format, actual_size))
  190. return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv);
  191. palette.ensure_capacity(palette_size);
  192. for (size_t i = 0; i < palette_size; ++i) {
  193. if (!read(palette[i]))
  194. return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv);
  195. }
  196. if (stream.remaining() < actual_size)
  197. return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv);
  198. auto data = stream.bytes().slice(stream.offset(), actual_size);
  199. auto bitmap = TRY(Bitmap::try_create(format, { width, height }, scale_factor));
  200. bitmap->m_palette = new ARGB32[palette_size];
  201. memcpy(bitmap->m_palette, palette.data(), palette_size * sizeof(ARGB32));
  202. data.copy_to({ bitmap->scanline(0), bitmap->size_in_bytes() });
  203. return bitmap;
  204. }
  205. ByteBuffer Bitmap::serialize_to_byte_buffer() const
  206. {
  207. // FIXME: Somehow handle possible OOM situation here.
  208. auto buffer = ByteBuffer::create_uninitialized(sizeof(size_t) + 4 * sizeof(unsigned) + sizeof(BitmapFormat) + sizeof(ARGB32) * palette_size(m_format) + size_in_bytes()).release_value_but_fixme_should_propagate_errors();
  209. OutputMemoryStream stream { buffer };
  210. auto write = [&]<typename T>(T value) {
  211. if (stream.write({ &value, sizeof(T) }) != sizeof(T))
  212. return false;
  213. return true;
  214. };
  215. auto palette = palette_to_vector();
  216. if (!write(size_in_bytes()) || !write((unsigned)size().width()) || !write((unsigned)size().height()) || !write((unsigned)scale()) || !write(m_format) || !write((unsigned)palette.size()))
  217. return {};
  218. for (auto& p : palette) {
  219. if (!write(p))
  220. return {};
  221. }
  222. auto size = size_in_bytes();
  223. VERIFY(stream.remaining() == size);
  224. if (stream.write({ scanline(0), size }) != size)
  225. return {};
  226. return buffer;
  227. }
  228. Bitmap::Bitmap(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize const& size, int scale_factor, Vector<ARGB32> const& palette)
  229. : m_size(size)
  230. , m_scale(scale_factor)
  231. , m_data(buffer.data<void>())
  232. , m_pitch(minimum_pitch(size.width() * scale_factor, format))
  233. , m_format(format)
  234. , m_buffer(move(buffer))
  235. {
  236. VERIFY(!is_indexed() || !palette.is_empty());
  237. VERIFY(!size_would_overflow(format, size, scale_factor));
  238. if (is_indexed(m_format))
  239. allocate_palette_from_format(m_format, palette);
  240. }
  241. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::clone() const
  242. {
  243. auto new_bitmap = TRY(Bitmap::try_create(format(), size(), scale()));
  244. VERIFY(size_in_bytes() == new_bitmap->size_in_bytes());
  245. memcpy(new_bitmap->scanline(0), scanline(0), size_in_bytes());
  246. return new_bitmap;
  247. }
  248. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
  249. {
  250. auto new_bitmap = TRY(Gfx::Bitmap::try_create(this->format(), { height(), width() }, scale()));
  251. auto w = this->physical_width();
  252. auto h = this->physical_height();
  253. for (int i = 0; i < w; i++) {
  254. for (int j = 0; j < h; j++) {
  255. Color color;
  256. if (rotation_direction == Gfx::RotationDirection::CounterClockwise)
  257. color = this->get_pixel(w - i - 1, j);
  258. else
  259. color = this->get_pixel(i, h - j - 1);
  260. new_bitmap->set_pixel(j, i, color);
  261. }
  262. }
  263. return new_bitmap;
  264. }
  265. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::flipped(Gfx::Orientation orientation) const
  266. {
  267. auto new_bitmap = TRY(Gfx::Bitmap::try_create(this->format(), { width(), height() }, scale()));
  268. auto w = this->physical_width();
  269. auto h = this->physical_height();
  270. for (int i = 0; i < w; i++) {
  271. for (int j = 0; j < h; j++) {
  272. Color color = this->get_pixel(i, j);
  273. if (orientation == Orientation::Vertical)
  274. new_bitmap->set_pixel(i, h - j - 1, color);
  275. else
  276. new_bitmap->set_pixel(w - i - 1, j, color);
  277. }
  278. }
  279. return new_bitmap;
  280. }
  281. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(int sx, int sy) const
  282. {
  283. VERIFY(sx >= 0 && sy >= 0);
  284. if (sx == 1 && sy == 1)
  285. return NonnullRefPtr { *this };
  286. auto new_bitmap = TRY(Gfx::Bitmap::try_create(format(), { width() * sx, height() * sy }, scale()));
  287. auto old_width = physical_width();
  288. auto old_height = physical_height();
  289. for (int y = 0; y < old_height; y++) {
  290. for (int x = 0; x < old_width; x++) {
  291. auto color = get_pixel(x, y);
  292. auto base_x = x * sx;
  293. auto base_y = y * sy;
  294. for (int new_y = base_y; new_y < base_y + sy; new_y++) {
  295. for (int new_x = base_x; new_x < base_x + sx; new_x++) {
  296. new_bitmap->set_pixel(new_x, new_y, color);
  297. }
  298. }
  299. }
  300. }
  301. return new_bitmap;
  302. }
  303. // http://fourier.eng.hmc.edu/e161/lectures/resize/node3.html
  304. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(float sx, float sy) const
  305. {
  306. VERIFY(sx >= 0.0f && sy >= 0.0f);
  307. if (floorf(sx) == sx && floorf(sy) == sy)
  308. return scaled(static_cast<int>(sx), static_cast<int>(sy));
  309. int scaled_width = (int)ceilf(sx * (float)width());
  310. int scaled_height = (int)ceilf(sy * (float)height());
  311. auto new_bitmap = TRY(Gfx::Bitmap::try_create(format(), { scaled_width, scaled_height }, scale()));
  312. auto old_width = physical_width();
  313. auto old_height = physical_height();
  314. auto new_width = new_bitmap->physical_width();
  315. auto new_height = new_bitmap->physical_height();
  316. // The interpolation goes out of bounds on the bottom- and right-most edges.
  317. // We handle those in two specialized loops not only to make them faster, but
  318. // also to avoid four branch checks for every pixel.
  319. for (int y = 0; y < new_height - 1; y++) {
  320. for (int x = 0; x < new_width - 1; x++) {
  321. auto p = static_cast<float>(x) * static_cast<float>(old_width - 1) / static_cast<float>(new_width - 1);
  322. auto q = static_cast<float>(y) * static_cast<float>(old_height - 1) / static_cast<float>(new_height - 1);
  323. int i = floorf(p);
  324. int j = floorf(q);
  325. float u = p - static_cast<float>(i);
  326. float v = q - static_cast<float>(j);
  327. auto a = get_pixel(i, j);
  328. auto b = get_pixel(i + 1, j);
  329. auto c = get_pixel(i, j + 1);
  330. auto d = get_pixel(i + 1, j + 1);
  331. auto e = a.interpolate(b, u);
  332. auto f = c.interpolate(d, u);
  333. auto color = e.interpolate(f, v);
  334. new_bitmap->set_pixel(x, y, color);
  335. }
  336. }
  337. // Bottom strip (excluding last pixel)
  338. auto old_bottom_y = old_height - 1;
  339. auto new_bottom_y = new_height - 1;
  340. for (int x = 0; x < new_width - 1; x++) {
  341. auto p = static_cast<float>(x) * static_cast<float>(old_width - 1) / static_cast<float>(new_width - 1);
  342. int i = floorf(p);
  343. float u = p - static_cast<float>(i);
  344. auto a = get_pixel(i, old_bottom_y);
  345. auto b = get_pixel(i + 1, old_bottom_y);
  346. auto color = a.interpolate(b, u);
  347. new_bitmap->set_pixel(x, new_bottom_y, color);
  348. }
  349. // Right strip (excluding last pixel)
  350. auto old_right_x = old_width - 1;
  351. auto new_right_x = new_width - 1;
  352. for (int y = 0; y < new_height - 1; y++) {
  353. auto q = static_cast<float>(y) * static_cast<float>(old_height - 1) / static_cast<float>(new_height - 1);
  354. int j = floorf(q);
  355. float v = q - static_cast<float>(j);
  356. auto c = get_pixel(old_right_x, j);
  357. auto d = get_pixel(old_right_x, j + 1);
  358. auto color = c.interpolate(d, v);
  359. new_bitmap->set_pixel(new_right_x, y, color);
  360. }
  361. // Bottom-right pixel
  362. new_bitmap->set_pixel(new_width - 1, new_height - 1, get_pixel(physical_width() - 1, physical_height() - 1));
  363. return new_bitmap;
  364. }
  365. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::cropped(Gfx::IntRect crop) const
  366. {
  367. auto new_bitmap = TRY(Gfx::Bitmap::try_create(format(), { crop.width(), crop.height() }, 1));
  368. for (int y = 0; y < crop.height(); ++y) {
  369. for (int x = 0; x < crop.width(); ++x) {
  370. int global_x = x + crop.left();
  371. int global_y = y + crop.top();
  372. if (global_x >= physical_width() || global_y >= physical_height() || global_x < 0 || global_y < 0) {
  373. new_bitmap->set_pixel(x, y, Gfx::Color::Black);
  374. } else {
  375. new_bitmap->set_pixel(x, y, get_pixel(global_x, global_y));
  376. }
  377. }
  378. }
  379. return new_bitmap;
  380. }
  381. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::to_bitmap_backed_by_anonymous_buffer() const
  382. {
  383. if (m_buffer.is_valid())
  384. return NonnullRefPtr { *this };
  385. auto buffer = TRY(Core::AnonymousBuffer::create_with_size(round_up_to_power_of_two(size_in_bytes(), PAGE_SIZE)));
  386. auto bitmap = TRY(Bitmap::try_create_with_anonymous_buffer(m_format, move(buffer), size(), scale(), palette_to_vector()));
  387. memcpy(bitmap->scanline(0), scanline(0), size_in_bytes());
  388. return bitmap;
  389. }
  390. Bitmap::~Bitmap()
  391. {
  392. if (m_needs_munmap) {
  393. int rc = munmap(m_data, size_in_bytes());
  394. VERIFY(rc == 0);
  395. }
  396. m_data = nullptr;
  397. delete[] m_palette;
  398. }
  399. void Bitmap::set_mmap_name([[maybe_unused]] String const& name)
  400. {
  401. VERIFY(m_needs_munmap);
  402. #ifdef __serenity__
  403. ::set_mmap_name(m_data, size_in_bytes(), name.characters());
  404. #endif
  405. }
  406. void Bitmap::fill(Color color)
  407. {
  408. VERIFY(!is_indexed(m_format));
  409. for (int y = 0; y < physical_height(); ++y) {
  410. auto* scanline = this->scanline(y);
  411. fast_u32_fill(scanline, color.value(), physical_width());
  412. }
  413. }
  414. void Bitmap::set_volatile()
  415. {
  416. if (m_volatile)
  417. return;
  418. #ifdef __serenity__
  419. int rc = madvise(m_data, size_in_bytes(), MADV_SET_VOLATILE);
  420. if (rc < 0) {
  421. perror("madvise(MADV_SET_VOLATILE)");
  422. VERIFY_NOT_REACHED();
  423. }
  424. #endif
  425. m_volatile = true;
  426. }
  427. [[nodiscard]] bool Bitmap::set_nonvolatile(bool& was_purged)
  428. {
  429. if (!m_volatile) {
  430. was_purged = false;
  431. return true;
  432. }
  433. #ifdef __serenity__
  434. int rc = madvise(m_data, size_in_bytes(), MADV_SET_NONVOLATILE);
  435. if (rc < 0) {
  436. if (errno == ENOMEM) {
  437. was_purged = true;
  438. return false;
  439. }
  440. perror("madvise(MADV_SET_NONVOLATILE)");
  441. VERIFY_NOT_REACHED();
  442. }
  443. was_purged = rc != 0;
  444. #endif
  445. m_volatile = false;
  446. return true;
  447. }
  448. Gfx::ShareableBitmap Bitmap::to_shareable_bitmap() const
  449. {
  450. auto bitmap_or_error = to_bitmap_backed_by_anonymous_buffer();
  451. if (bitmap_or_error.is_error())
  452. return {};
  453. return Gfx::ShareableBitmap { bitmap_or_error.release_value_but_fixme_should_propagate_errors(), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  454. }
  455. ErrorOr<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, IntSize const& size, int scale_factor)
  456. {
  457. if (size_would_overflow(format, size, scale_factor))
  458. return Error::from_string_literal("Gfx::Bitmap backing store size overflow"sv);
  459. auto const pitch = minimum_pitch(size.width() * scale_factor, format);
  460. auto const data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  461. int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  462. #ifdef __serenity__
  463. map_flags |= MAP_PURGEABLE;
  464. void* data = mmap_with_name(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0, String::formatted("GraphicsBitmap [{}]", size).characters());
  465. #else
  466. void* data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0);
  467. #endif
  468. if (data == MAP_FAILED)
  469. return Error::from_errno(errno);
  470. return BackingStore { data, pitch, data_size_in_bytes };
  471. }
  472. void Bitmap::allocate_palette_from_format(BitmapFormat format, Vector<ARGB32> const& source_palette)
  473. {
  474. size_t size = palette_size(format);
  475. if (size == 0)
  476. return;
  477. m_palette = new ARGB32[size];
  478. if (!source_palette.is_empty()) {
  479. VERIFY(source_palette.size() == size);
  480. memcpy(m_palette, source_palette.data(), size * sizeof(ARGB32));
  481. }
  482. }
  483. Vector<ARGB32> Bitmap::palette_to_vector() const
  484. {
  485. Vector<ARGB32> vector;
  486. auto size = palette_size(m_format);
  487. vector.ensure_capacity(size);
  488. for (size_t i = 0; i < size; ++i)
  489. vector.unchecked_append(palette_color(i).value());
  490. return vector;
  491. }
  492. bool Bitmap::visually_equals(Bitmap const& other) const
  493. {
  494. auto own_width = width();
  495. auto own_height = height();
  496. if (other.width() != own_width || other.height() != own_height)
  497. return false;
  498. for (auto y = 0; y < own_height; ++y) {
  499. for (auto x = 0; x < own_width; ++x) {
  500. if (get_pixel(x, y) != other.get_pixel(x, y))
  501. return false;
  502. }
  503. }
  504. return true;
  505. }
  506. }