Bitmap.cpp 23 KB

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