Bitmap.cpp 22 KB

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