Bitmap.cpp 24 KB

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