Bitmap.cpp 24 KB

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