Bitmap.cpp 22 KB

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