Bitmap.cpp 22 KB

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