Bitmap.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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/ByteString.h>
  9. #include <AK/Checked.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::BGRx8888:
  39. case StorageFormat::BGRA8888:
  40. case StorageFormat::RGBA8888:
  41. element_size = 4;
  42. break;
  43. default:
  44. VERIFY_NOT_REACHED();
  45. }
  46. return physical_width * element_size;
  47. }
  48. static bool size_would_overflow(BitmapFormat format, IntSize size, int scale_factor)
  49. {
  50. if (size.width() < 0 || size.height() < 0)
  51. return true;
  52. // This check is a bit arbitrary, but should protect us from most shenanigans:
  53. if (size.width() >= INT16_MAX || size.height() >= INT16_MAX || scale_factor < 1 || scale_factor > 4)
  54. return true;
  55. // In contrast, this check is absolutely necessary:
  56. size_t pitch = Bitmap::minimum_pitch(size.width() * scale_factor, format);
  57. return Checked<size_t>::multiplication_would_overflow(pitch, size.height() * scale_factor);
  58. }
  59. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create(BitmapFormat format, IntSize size, int scale_factor)
  60. {
  61. auto backing_store = TRY(Bitmap::allocate_backing_store(format, size, scale_factor));
  62. return AK::adopt_nonnull_ref_or_enomem(new (nothrow) Bitmap(format, size, scale_factor, backing_store));
  63. }
  64. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_shareable(BitmapFormat format, IntSize size, int scale_factor)
  65. {
  66. if (size_would_overflow(format, size, scale_factor))
  67. return Error::from_string_literal("Gfx::Bitmap::create_shareable size overflow");
  68. auto const pitch = minimum_pitch(size.width() * scale_factor, format);
  69. auto const data_size = size_in_bytes(pitch, size.height() * scale_factor);
  70. auto buffer = TRY(Core::AnonymousBuffer::create_with_size(round_up_to_power_of_two(data_size, PAGE_SIZE)));
  71. auto bitmap = TRY(Bitmap::create_with_anonymous_buffer(format, buffer, size, scale_factor));
  72. return bitmap;
  73. }
  74. Bitmap::Bitmap(BitmapFormat format, IntSize size, int scale_factor, BackingStore const& backing_store)
  75. : m_size(size)
  76. , m_scale(scale_factor)
  77. , m_data(backing_store.data)
  78. , m_pitch(backing_store.pitch)
  79. , m_format(format)
  80. {
  81. VERIFY(!m_size.is_empty());
  82. VERIFY(!size_would_overflow(format, size, scale_factor));
  83. VERIFY(m_data);
  84. VERIFY(backing_store.size_in_bytes == size_in_bytes());
  85. m_needs_munmap = true;
  86. }
  87. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_wrapper(BitmapFormat format, IntSize size, int scale_factor, size_t pitch, void* data)
  88. {
  89. if (size_would_overflow(format, size, scale_factor))
  90. return Error::from_string_literal("Gfx::Bitmap::create_wrapper size overflow");
  91. return adopt_ref(*new Bitmap(format, size, scale_factor, pitch, data));
  92. }
  93. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::load_from_file(StringView path, int scale_factor, Optional<IntSize> ideal_size)
  94. {
  95. if (scale_factor > 1 && path.starts_with("/res/"sv)) {
  96. auto load_scaled_bitmap = [](StringView path, int scale_factor, Optional<IntSize> ideal_size) -> ErrorOr<NonnullRefPtr<Bitmap>> {
  97. LexicalPath lexical_path { path };
  98. StringBuilder highdpi_icon_path;
  99. TRY(highdpi_icon_path.try_appendff("{}/{}-{}x.{}", lexical_path.dirname(), lexical_path.title(), scale_factor, lexical_path.extension()));
  100. auto highdpi_icon_string = highdpi_icon_path.string_view();
  101. auto file = TRY(Core::File::open(highdpi_icon_string, Core::File::OpenMode::Read));
  102. auto bitmap = TRY(load_from_file(move(file), highdpi_icon_string, ideal_size));
  103. if (bitmap->width() % scale_factor != 0 || bitmap->height() % scale_factor != 0)
  104. return Error::from_string_literal("Bitmap::load_from_file: HighDPI image size should be divisible by scale factor");
  105. bitmap->m_size.set_width(bitmap->width() / scale_factor);
  106. bitmap->m_size.set_height(bitmap->height() / scale_factor);
  107. bitmap->m_scale = scale_factor;
  108. return bitmap;
  109. };
  110. auto scaled_bitmap_or_error = load_scaled_bitmap(path, scale_factor, ideal_size);
  111. if (!scaled_bitmap_or_error.is_error())
  112. return scaled_bitmap_or_error.release_value();
  113. auto error = scaled_bitmap_or_error.release_error();
  114. if (!(error.is_syscall() && error.code() == ENOENT)) {
  115. dbgln("Couldn't load scaled bitmap: {}", error);
  116. dbgln("Trying base scale instead.");
  117. }
  118. }
  119. auto file = TRY(Core::File::open(path, Core::File::OpenMode::Read));
  120. return load_from_file(move(file), path, ideal_size);
  121. }
  122. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::load_from_file(NonnullOwnPtr<Core::File> file, StringView path, Optional<IntSize> ideal_size)
  123. {
  124. auto mapped_file = TRY(Core::MappedFile::map_from_file(move(file), path));
  125. auto mime_type = Core::guess_mime_type_based_on_filename(path);
  126. return load_from_bytes(mapped_file->bytes(), ideal_size, mime_type);
  127. }
  128. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::load_from_bytes(ReadonlyBytes bytes, Optional<IntSize> ideal_size, Optional<ByteString> mine_type)
  129. {
  130. if (auto decoder = TRY(ImageDecoder::try_create_for_raw_bytes(bytes, mine_type))) {
  131. auto frame = TRY(decoder->frame(0, ideal_size));
  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. }
  148. static bool check_size(IntSize size, int scale_factor, BitmapFormat format, unsigned actual_size)
  149. {
  150. // FIXME: Code duplication of size_in_bytes() and m_pitch
  151. unsigned expected_size_min = Bitmap::minimum_pitch(size.width() * scale_factor, format) * size.height() * scale_factor;
  152. unsigned expected_size_max = round_up_to_power_of_two(expected_size_min, PAGE_SIZE);
  153. if (expected_size_min > actual_size || actual_size > expected_size_max) {
  154. // Getting here is most likely an error.
  155. dbgln("Constructing a shared bitmap for format {} and size {} @ {}x, which demands {} bytes, which rounds up to at most {}.",
  156. static_cast<int>(format),
  157. size,
  158. scale_factor,
  159. expected_size_min,
  160. expected_size_max);
  161. dbgln("However, we were given {} bytes, which is outside this range?! Refusing cowardly.", actual_size);
  162. return false;
  163. }
  164. return true;
  165. }
  166. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_with_anonymous_buffer(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize size, int scale_factor)
  167. {
  168. if (size_would_overflow(format, size, scale_factor))
  169. return Error::from_string_literal("Gfx::Bitmap::create_with_anonymous_buffer size overflow");
  170. return adopt_nonnull_ref_or_enomem(new (nothrow) Bitmap(format, move(buffer), size, scale_factor));
  171. }
  172. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_from_serialized_byte_buffer(ByteBuffer&& buffer)
  173. {
  174. return create_from_serialized_bytes(buffer.bytes());
  175. }
  176. /// Read a bitmap as described by:
  177. /// - actual size
  178. /// - width
  179. /// - height
  180. /// - scale_factor
  181. /// - format
  182. /// - image data (= actual size * u8)
  183. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_from_serialized_bytes(ReadonlyBytes bytes)
  184. {
  185. FixedMemoryStream stream { bytes };
  186. auto actual_size = TRY(stream.read_value<size_t>());
  187. auto width = TRY(stream.read_value<unsigned>());
  188. auto height = TRY(stream.read_value<unsigned>());
  189. auto scale_factor = TRY(stream.read_value<unsigned>());
  190. auto format = TRY(stream.read_value<BitmapFormat>());
  191. if (format > BitmapFormat::LastValid || format < BitmapFormat::FirstValid)
  192. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  193. if (!check_size({ width, height }, scale_factor, format, actual_size))
  194. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  195. if (TRY(stream.size()) - TRY(stream.tell()) < actual_size)
  196. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  197. auto data = bytes.slice(TRY(stream.tell()), actual_size);
  198. auto bitmap = TRY(Bitmap::create(format, { width, height }, scale_factor));
  199. data.copy_to({ bitmap->scanline(0), bitmap->size_in_bytes() });
  200. return bitmap;
  201. }
  202. ErrorOr<ByteBuffer> Bitmap::serialize_to_byte_buffer() const
  203. {
  204. auto buffer = TRY(ByteBuffer::create_uninitialized(sizeof(size_t) + 3 * sizeof(unsigned) + sizeof(BitmapFormat) + size_in_bytes()));
  205. FixedMemoryStream stream { buffer.span() };
  206. TRY(stream.write_value(size_in_bytes()));
  207. TRY(stream.write_value<unsigned>(size().width()));
  208. TRY(stream.write_value<unsigned>(size().height()));
  209. TRY(stream.write_value<unsigned>(scale()));
  210. TRY(stream.write_value(m_format));
  211. auto size = size_in_bytes();
  212. TRY(stream.write_until_depleted({ scanline(0), size }));
  213. VERIFY(TRY(stream.tell()) == TRY(stream.size()));
  214. return buffer;
  215. }
  216. Bitmap::Bitmap(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize size, int scale_factor)
  217. : m_size(size)
  218. , m_scale(scale_factor)
  219. , m_data(buffer.data<void>())
  220. , m_pitch(minimum_pitch(size.width() * scale_factor, format))
  221. , m_format(format)
  222. , m_buffer(move(buffer))
  223. {
  224. VERIFY(!size_would_overflow(format, size, scale_factor));
  225. }
  226. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::clone() const
  227. {
  228. auto new_bitmap = TRY(Bitmap::create(format(), size(), scale()));
  229. VERIFY(size_in_bytes() == new_bitmap->size_in_bytes());
  230. memcpy(new_bitmap->scanline(0), scanline(0), size_in_bytes());
  231. return new_bitmap;
  232. }
  233. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
  234. {
  235. if (rotation_direction == Gfx::RotationDirection::Flip) {
  236. auto new_bitmap = TRY(Gfx::Bitmap::create(format(), { width(), height() }, scale()));
  237. auto w = this->physical_width();
  238. auto h = this->physical_height();
  239. for (int i = 0; i < w; i++) {
  240. for (int j = 0; j < h; j++)
  241. new_bitmap->set_pixel(w - i - 1, h - j - 1, this->get_pixel(i, j));
  242. }
  243. return new_bitmap;
  244. }
  245. auto new_bitmap = TRY(Gfx::Bitmap::create(this->format(), { height(), width() }, scale()));
  246. auto w = this->physical_width();
  247. auto h = this->physical_height();
  248. for (int i = 0; i < w; i++) {
  249. for (int j = 0; j < h; j++) {
  250. Color color;
  251. if (rotation_direction == Gfx::RotationDirection::CounterClockwise)
  252. color = this->get_pixel(w - i - 1, j);
  253. else
  254. color = this->get_pixel(i, h - j - 1);
  255. new_bitmap->set_pixel(j, i, color);
  256. }
  257. }
  258. return new_bitmap;
  259. }
  260. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::flipped(Gfx::Orientation orientation) const
  261. {
  262. auto new_bitmap = TRY(Gfx::Bitmap::create(this->format(), { width(), height() }, scale()));
  263. auto w = this->physical_width();
  264. auto h = this->physical_height();
  265. for (int i = 0; i < w; i++) {
  266. for (int j = 0; j < h; j++) {
  267. Color color = this->get_pixel(i, j);
  268. if (orientation == Orientation::Vertical)
  269. new_bitmap->set_pixel(i, h - j - 1, color);
  270. else
  271. new_bitmap->set_pixel(w - i - 1, j, color);
  272. }
  273. }
  274. return new_bitmap;
  275. }
  276. void Bitmap::apply_mask(Gfx::Bitmap const& mask, MaskKind mask_kind)
  277. {
  278. VERIFY(size() == mask.size());
  279. for (int y = 0; y < height(); y++) {
  280. for (int x = 0; x < width(); x++) {
  281. auto color = get_pixel(x, y);
  282. auto mask_color = mask.get_pixel(x, y);
  283. if (mask_kind == MaskKind::Luminance) {
  284. color = color.with_alpha(color.alpha() * mask_color.alpha() * mask_color.luminosity() / (255 * 255));
  285. } else {
  286. VERIFY(mask_kind == MaskKind::Alpha);
  287. color = color.with_alpha(color.alpha() * mask_color.alpha() / 255);
  288. }
  289. set_pixel(x, y, color);
  290. }
  291. }
  292. }
  293. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(int sx, int sy) const
  294. {
  295. VERIFY(sx >= 0 && sy >= 0);
  296. if (sx == 1 && sy == 1)
  297. return clone();
  298. auto new_bitmap = TRY(Gfx::Bitmap::create(format(), { width() * sx, height() * sy }, scale()));
  299. auto old_width = physical_width();
  300. auto old_height = physical_height();
  301. for (int y = 0; y < old_height; y++) {
  302. for (int x = 0; x < old_width; x++) {
  303. auto color = get_pixel(x, y);
  304. auto base_x = x * sx;
  305. auto base_y = y * sy;
  306. for (int new_y = base_y; new_y < base_y + sy; new_y++) {
  307. for (int new_x = base_x; new_x < base_x + sx; new_x++) {
  308. new_bitmap->set_pixel(new_x, new_y, color);
  309. }
  310. }
  311. }
  312. }
  313. return new_bitmap;
  314. }
  315. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(float sx, float sy) const
  316. {
  317. VERIFY(sx >= 0.0f && sy >= 0.0f);
  318. if (floorf(sx) == sx && floorf(sy) == sy)
  319. return scaled(static_cast<int>(sx), static_cast<int>(sy));
  320. int scaled_width = (int)ceilf(sx * (float)width());
  321. int scaled_height = (int)ceilf(sy * (float)height());
  322. return scaled_to_size({ scaled_width, scaled_height });
  323. }
  324. // http://fourier.eng.hmc.edu/e161/lectures/resize/node3.html
  325. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled_to_size(Gfx::IntSize size) const
  326. {
  327. auto new_bitmap = TRY(Gfx::Bitmap::create(format(), size, scale()));
  328. auto old_width = physical_width();
  329. auto old_height = physical_height();
  330. auto new_width = new_bitmap->physical_width();
  331. auto new_height = new_bitmap->physical_height();
  332. if (old_width == 1 && old_height == 1) {
  333. new_bitmap->fill(get_pixel(0, 0));
  334. return new_bitmap;
  335. }
  336. if (old_width > 1 && old_height > 1) {
  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.mixed_with(b, u);
  353. auto f = c.mixed_with(d, u);
  354. auto color = e.mixed_with(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.mixed_with(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.mixed_with(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. } else if (old_height == 1) {
  386. // Copy horizontal strip multiple times (excluding last pixel to out of bounds).
  387. auto old_bottom_y = old_height - 1;
  388. for (int x = 0; x < new_width - 1; x++) {
  389. auto p = static_cast<float>(x) * static_cast<float>(old_width - 1) / static_cast<float>(new_width - 1);
  390. int i = floorf(p);
  391. float u = p - static_cast<float>(i);
  392. auto a = get_pixel(i, old_bottom_y);
  393. auto b = get_pixel(i + 1, old_bottom_y);
  394. auto color = a.mixed_with(b, u);
  395. for (int new_bottom_y = 0; new_bottom_y < new_height; new_bottom_y++) {
  396. // Interpolate color only once and then copy into all columns.
  397. new_bitmap->set_pixel(x, new_bottom_y, color);
  398. }
  399. }
  400. for (int new_bottom_y = 0; new_bottom_y < new_height; new_bottom_y++) {
  401. // Copy last pixel of horizontal strip
  402. new_bitmap->set_pixel(new_width - 1, new_bottom_y, get_pixel(physical_width() - 1, old_bottom_y));
  403. }
  404. return new_bitmap;
  405. } else if (old_width == 1) {
  406. // Copy vertical strip multiple times (excluding last pixel to avoid out of bounds).
  407. auto old_right_x = old_width - 1;
  408. for (int y = 0; y < new_height - 1; y++) {
  409. auto q = static_cast<float>(y) * static_cast<float>(old_height - 1) / static_cast<float>(new_height - 1);
  410. int j = floorf(q);
  411. float v = q - static_cast<float>(j);
  412. auto c = get_pixel(old_right_x, j);
  413. auto d = get_pixel(old_right_x, j + 1);
  414. auto color = c.mixed_with(d, v);
  415. for (int new_right_x = 0; new_right_x < new_width; new_right_x++) {
  416. // Interpolate color only once and copy into all rows.
  417. new_bitmap->set_pixel(new_right_x, y, color);
  418. }
  419. }
  420. for (int new_right_x = 0; new_right_x < new_width; new_right_x++) {
  421. // Copy last pixel of vertical strip
  422. new_bitmap->set_pixel(new_right_x, new_height - 1, get_pixel(old_right_x, physical_height() - 1));
  423. }
  424. }
  425. return new_bitmap;
  426. }
  427. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::cropped(Gfx::IntRect crop, Optional<BitmapFormat> new_bitmap_format) const
  428. {
  429. auto new_bitmap = TRY(Gfx::Bitmap::create(new_bitmap_format.value_or(format()), { crop.width(), crop.height() }, scale()));
  430. auto scaled_crop = crop * scale();
  431. for (int y = 0; y < scaled_crop.height(); ++y) {
  432. for (int x = 0; x < scaled_crop.width(); ++x) {
  433. int global_x = x + scaled_crop.left();
  434. int global_y = y + scaled_crop.top();
  435. if (global_x >= physical_width() || global_y >= physical_height() || global_x < 0 || global_y < 0) {
  436. new_bitmap->set_pixel(x, y, Gfx::Color::Black);
  437. } else {
  438. new_bitmap->set_pixel(x, y, get_pixel(global_x, global_y));
  439. }
  440. }
  441. }
  442. return new_bitmap;
  443. }
  444. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::to_bitmap_backed_by_anonymous_buffer() const
  445. {
  446. if (m_buffer.is_valid()) {
  447. // FIXME: The const_cast here is awkward.
  448. return NonnullRefPtr { const_cast<Bitmap&>(*this) };
  449. }
  450. auto buffer = TRY(Core::AnonymousBuffer::create_with_size(round_up_to_power_of_two(size_in_bytes(), PAGE_SIZE)));
  451. auto bitmap = TRY(Bitmap::create_with_anonymous_buffer(m_format, move(buffer), size(), scale()));
  452. memcpy(bitmap->scanline(0), scanline(0), size_in_bytes());
  453. return bitmap;
  454. }
  455. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::inverted() const
  456. {
  457. auto inverted_bitmap = TRY(clone());
  458. for (auto y = 0; y < height(); y++) {
  459. for (auto x = 0; x < width(); x++)
  460. inverted_bitmap->set_pixel(x, y, get_pixel(x, y).inverted());
  461. }
  462. return inverted_bitmap;
  463. }
  464. Bitmap::~Bitmap()
  465. {
  466. if (m_needs_munmap) {
  467. int rc = munmap(m_data, size_in_bytes());
  468. VERIFY(rc == 0);
  469. }
  470. m_data = nullptr;
  471. }
  472. void Bitmap::strip_alpha_channel()
  473. {
  474. VERIFY(m_format == BitmapFormat::BGRA8888 || m_format == BitmapFormat::BGRx8888);
  475. for (ARGB32& pixel : *this)
  476. pixel = 0xff000000 | (pixel & 0xffffff);
  477. m_format = BitmapFormat::BGRx8888;
  478. }
  479. void Bitmap::fill(Color color)
  480. {
  481. for (int y = 0; y < physical_height(); ++y) {
  482. auto* scanline = this->scanline(y);
  483. fast_u32_fill(scanline, color.value(), physical_width());
  484. }
  485. }
  486. void Bitmap::set_volatile()
  487. {
  488. if (m_volatile)
  489. return;
  490. #ifdef AK_OS_SERENITY
  491. int rc = madvise(m_data, size_in_bytes(), MADV_SET_VOLATILE);
  492. if (rc < 0) {
  493. perror("madvise(MADV_SET_VOLATILE)");
  494. VERIFY_NOT_REACHED();
  495. }
  496. #endif
  497. m_volatile = true;
  498. }
  499. [[nodiscard]] bool Bitmap::set_nonvolatile(bool& was_purged)
  500. {
  501. if (!m_volatile) {
  502. was_purged = false;
  503. return true;
  504. }
  505. #ifdef AK_OS_SERENITY
  506. int rc = madvise(m_data, size_in_bytes(), MADV_SET_NONVOLATILE);
  507. if (rc < 0) {
  508. if (errno == ENOMEM) {
  509. was_purged = true;
  510. return false;
  511. }
  512. perror("madvise(MADV_SET_NONVOLATILE)");
  513. VERIFY_NOT_REACHED();
  514. }
  515. was_purged = rc != 0;
  516. #endif
  517. m_volatile = false;
  518. return true;
  519. }
  520. Gfx::ShareableBitmap Bitmap::to_shareable_bitmap() const
  521. {
  522. auto bitmap_or_error = to_bitmap_backed_by_anonymous_buffer();
  523. if (bitmap_or_error.is_error())
  524. return {};
  525. return Gfx::ShareableBitmap { bitmap_or_error.release_value_but_fixme_should_propagate_errors(), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  526. }
  527. ErrorOr<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, IntSize size, int scale_factor)
  528. {
  529. if (size_would_overflow(format, size, scale_factor))
  530. return Error::from_string_literal("Gfx::Bitmap backing store size overflow");
  531. auto const pitch = minimum_pitch(size.width() * scale_factor, format);
  532. auto const data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  533. int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  534. #ifdef AK_OS_SERENITY
  535. map_flags |= MAP_PURGEABLE;
  536. void* data = mmap_with_name(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0, ByteString::formatted("GraphicsBitmap [{}]", size).characters());
  537. #else
  538. void* data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, -1, 0);
  539. #endif
  540. if (data == MAP_FAILED)
  541. return Error::from_errno(errno);
  542. return BackingStore { data, pitch, data_size_in_bytes };
  543. }
  544. bool Bitmap::visually_equals(Bitmap const& other) const
  545. {
  546. auto own_width = width();
  547. auto own_height = height();
  548. if (other.width() != own_width || other.height() != own_height)
  549. return false;
  550. for (auto y = 0; y < own_height; ++y) {
  551. for (auto x = 0; x < own_width; ++x) {
  552. if (get_pixel(x, y) != other.get_pixel(x, y))
  553. return false;
  554. }
  555. }
  556. return true;
  557. }
  558. Optional<Color> Bitmap::solid_color(u8 alpha_threshold) const
  559. {
  560. Optional<Color> color;
  561. for (auto y = 0; y < height(); ++y) {
  562. for (auto x = 0; x < width(); ++x) {
  563. auto const& pixel = get_pixel(x, y);
  564. if (has_alpha_channel() && pixel.alpha() <= alpha_threshold)
  565. continue;
  566. if (!color.has_value())
  567. color = pixel;
  568. else if (pixel != color)
  569. return {};
  570. }
  571. }
  572. return color;
  573. }
  574. void Bitmap::flood_visit_from_point(Gfx::IntPoint start_point, int threshold,
  575. Function<void(Gfx::IntPoint location)> pixel_reached)
  576. {
  577. VERIFY(rect().contains(start_point));
  578. auto target_color = get_pixel(start_point.x(), start_point.y());
  579. float threshold_normalized_squared = (threshold / 100.0f) * (threshold / 100.0f);
  580. Queue<Gfx::IntPoint> points_to_visit = Queue<Gfx::IntPoint>();
  581. points_to_visit.enqueue(start_point);
  582. pixel_reached(start_point);
  583. auto flood_mask = AK::Bitmap::create(width() * height(), false).release_value_but_fixme_should_propagate_errors();
  584. flood_mask.set(width() * start_point.y() + start_point.x(), true);
  585. // This implements a non-recursive flood fill. This is a breadth-first search of paintable neighbors
  586. // As we find neighbors that are reachable we call the location_reached callback, add them to the queue, and mark them in the mask
  587. while (!points_to_visit.is_empty()) {
  588. auto current_point = points_to_visit.dequeue();
  589. auto candidate_points = Array {
  590. current_point.moved_left(1),
  591. current_point.moved_right(1),
  592. current_point.moved_up(1),
  593. current_point.moved_down(1)
  594. };
  595. for (auto candidate_point : candidate_points) {
  596. auto flood_mask_index = width() * candidate_point.y() + candidate_point.x();
  597. if (!rect().contains(candidate_point))
  598. continue;
  599. auto pixel_color = get_pixel<Gfx::StorageFormat::BGRA8888>(candidate_point.x(), candidate_point.y());
  600. auto can_paint = pixel_color.distance_squared_to(target_color) <= threshold_normalized_squared;
  601. if (flood_mask.get(flood_mask_index) == false && can_paint) {
  602. points_to_visit.enqueue(candidate_point);
  603. pixel_reached(candidate_point);
  604. }
  605. flood_mask.set(flood_mask_index, true);
  606. }
  607. }
  608. }
  609. }