Bitmap.cpp 20 KB

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