Bitmap.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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, Optional<IntSize> ideal_size)
  98. {
  99. if (scale_factor > 1 && path.starts_with("/res/"sv)) {
  100. auto load_scaled_bitmap = [](StringView path, int scale_factor, Optional<IntSize> ideal_size) -> 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, ideal_size));
  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, ideal_size);
  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, ideal_size);
  125. }
  126. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::load_from_file(NonnullOwnPtr<Core::File> file, StringView path, Optional<IntSize> ideal_size)
  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. return load_from_bytes(mapped_file->bytes(), ideal_size, mime_type);
  131. }
  132. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::load_from_bytes(ReadonlyBytes bytes, Optional<IntSize> ideal_size, Optional<DeprecatedString> mine_type)
  133. {
  134. if (auto decoder = ImageDecoder::try_create_for_raw_bytes(bytes, mine_type)) {
  135. auto frame = TRY(decoder->frame(0, ideal_size));
  136. if (auto& bitmap = frame.image)
  137. return bitmap.release_nonnull();
  138. }
  139. return Error::from_string_literal("Gfx::Bitmap unable to load from file");
  140. }
  141. Bitmap::Bitmap(BitmapFormat format, IntSize size, int scale_factor, size_t pitch, void* data)
  142. : m_size(size)
  143. , m_scale(scale_factor)
  144. , m_data(data)
  145. , m_pitch(pitch)
  146. , m_format(format)
  147. {
  148. VERIFY(pitch >= minimum_pitch(size.width() * scale_factor, format));
  149. VERIFY(!size_would_overflow(format, size, scale_factor));
  150. // FIXME: assert that `data` is actually long enough!
  151. allocate_palette_from_format(format, {});
  152. }
  153. static bool check_size(IntSize size, int scale_factor, BitmapFormat format, unsigned actual_size)
  154. {
  155. // FIXME: Code duplication of size_in_bytes() and m_pitch
  156. unsigned expected_size_min = Bitmap::minimum_pitch(size.width() * scale_factor, format) * size.height() * scale_factor;
  157. unsigned expected_size_max = round_up_to_power_of_two(expected_size_min, PAGE_SIZE);
  158. if (expected_size_min > actual_size || actual_size > expected_size_max) {
  159. // Getting here is most likely an error.
  160. dbgln("Constructing a shared bitmap for format {} and size {} @ {}x, which demands {} bytes, which rounds up to at most {}.",
  161. static_cast<int>(format),
  162. size,
  163. scale_factor,
  164. expected_size_min,
  165. expected_size_max);
  166. dbgln("However, we were given {} bytes, which is outside this range?! Refusing cowardly.", actual_size);
  167. return false;
  168. }
  169. return true;
  170. }
  171. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_with_anonymous_buffer(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize size, int scale_factor, Vector<ARGB32> const& palette)
  172. {
  173. if (size_would_overflow(format, size, scale_factor))
  174. return Error::from_string_literal("Gfx::Bitmap::create_with_anonymous_buffer size overflow");
  175. return adopt_nonnull_ref_or_enomem(new (nothrow) Bitmap(format, move(buffer), size, scale_factor, palette));
  176. }
  177. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_from_serialized_byte_buffer(ByteBuffer&& buffer)
  178. {
  179. return create_from_serialized_bytes(buffer.bytes());
  180. }
  181. /// Read a bitmap as described by:
  182. /// - actual size
  183. /// - width
  184. /// - height
  185. /// - scale_factor
  186. /// - format
  187. /// - palette count
  188. /// - palette data (= palette count * BGRA8888)
  189. /// - image data (= actual size * u8)
  190. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::create_from_serialized_bytes(ReadonlyBytes bytes)
  191. {
  192. FixedMemoryStream stream { bytes };
  193. auto actual_size = TRY(stream.read_value<size_t>());
  194. auto width = TRY(stream.read_value<unsigned>());
  195. auto height = TRY(stream.read_value<unsigned>());
  196. auto scale_factor = TRY(stream.read_value<unsigned>());
  197. auto format = TRY(stream.read_value<BitmapFormat>());
  198. auto palette_size = TRY(stream.read_value<unsigned>());
  199. if (format > BitmapFormat::BGRA8888 || format < BitmapFormat::Indexed1)
  200. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  201. if (!check_size({ width, height }, scale_factor, format, actual_size))
  202. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  203. Vector<ARGB32> palette;
  204. palette.ensure_capacity(palette_size);
  205. for (size_t i = 0; i < palette_size; ++i) {
  206. palette[i] = TRY(stream.read_value<ARGB32>());
  207. }
  208. if (TRY(stream.size()) - TRY(stream.tell()) < actual_size)
  209. return Error::from_string_literal("Gfx::Bitmap::create_from_serialized_byte_buffer: decode failed");
  210. auto data = bytes.slice(TRY(stream.tell()), actual_size);
  211. auto bitmap = TRY(Bitmap::create(format, { width, height }, scale_factor));
  212. bitmap->m_palette = new ARGB32[palette_size];
  213. memcpy(bitmap->m_palette, palette.data(), palette_size * sizeof(ARGB32));
  214. data.copy_to({ bitmap->scanline(0), bitmap->size_in_bytes() });
  215. return bitmap;
  216. }
  217. ErrorOr<ByteBuffer> Bitmap::serialize_to_byte_buffer() const
  218. {
  219. auto buffer = TRY(ByteBuffer::create_uninitialized(sizeof(size_t) + 4 * sizeof(unsigned) + sizeof(BitmapFormat) + sizeof(ARGB32) * palette_size(m_format) + size_in_bytes()));
  220. FixedMemoryStream stream { buffer.span() };
  221. auto palette = palette_to_vector();
  222. TRY(stream.write_value(size_in_bytes()));
  223. TRY(stream.write_value<unsigned>(size().width()));
  224. TRY(stream.write_value<unsigned>(size().height()));
  225. TRY(stream.write_value<unsigned>(scale()));
  226. TRY(stream.write_value(m_format));
  227. TRY(stream.write_value<unsigned>(palette.size()));
  228. for (auto& p : palette) {
  229. TRY(stream.write_value(p));
  230. }
  231. auto size = size_in_bytes();
  232. TRY(stream.write_until_depleted({ scanline(0), size }));
  233. VERIFY(TRY(stream.tell()) == TRY(stream.size()));
  234. return buffer;
  235. }
  236. Bitmap::Bitmap(BitmapFormat format, Core::AnonymousBuffer buffer, IntSize size, int scale_factor, Vector<ARGB32> const& palette)
  237. : m_size(size)
  238. , m_scale(scale_factor)
  239. , m_data(buffer.data<void>())
  240. , m_pitch(minimum_pitch(size.width() * scale_factor, format))
  241. , m_format(format)
  242. , m_buffer(move(buffer))
  243. {
  244. VERIFY(!is_indexed() || !palette.is_empty());
  245. VERIFY(!size_would_overflow(format, size, scale_factor));
  246. if (is_indexed(m_format))
  247. allocate_palette_from_format(m_format, palette);
  248. }
  249. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::clone() const
  250. {
  251. auto new_bitmap = TRY(Bitmap::create(format(), size(), scale()));
  252. VERIFY(size_in_bytes() == new_bitmap->size_in_bytes());
  253. memcpy(new_bitmap->scanline(0), scanline(0), size_in_bytes());
  254. return new_bitmap;
  255. }
  256. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
  257. {
  258. auto new_bitmap = TRY(Gfx::Bitmap::create(this->format(), { height(), width() }, scale()));
  259. auto w = this->physical_width();
  260. auto h = this->physical_height();
  261. for (int i = 0; i < w; i++) {
  262. for (int j = 0; j < h; j++) {
  263. Color color;
  264. if (rotation_direction == Gfx::RotationDirection::CounterClockwise)
  265. color = this->get_pixel(w - i - 1, j);
  266. else
  267. color = this->get_pixel(i, h - j - 1);
  268. new_bitmap->set_pixel(j, i, color);
  269. }
  270. }
  271. return new_bitmap;
  272. }
  273. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::flipped(Gfx::Orientation orientation) const
  274. {
  275. auto new_bitmap = TRY(Gfx::Bitmap::create(this->format(), { width(), height() }, scale()));
  276. auto w = this->physical_width();
  277. auto h = this->physical_height();
  278. for (int i = 0; i < w; i++) {
  279. for (int j = 0; j < h; j++) {
  280. Color color = this->get_pixel(i, j);
  281. if (orientation == Orientation::Vertical)
  282. new_bitmap->set_pixel(i, h - j - 1, color);
  283. else
  284. new_bitmap->set_pixel(w - i - 1, j, color);
  285. }
  286. }
  287. return new_bitmap;
  288. }
  289. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(int sx, int sy) const
  290. {
  291. VERIFY(sx >= 0 && sy >= 0);
  292. if (sx == 1 && sy == 1)
  293. return clone();
  294. auto new_bitmap = TRY(Gfx::Bitmap::create(format(), { width() * sx, height() * sy }, scale()));
  295. auto old_width = physical_width();
  296. auto old_height = physical_height();
  297. for (int y = 0; y < old_height; y++) {
  298. for (int x = 0; x < old_width; x++) {
  299. auto color = get_pixel(x, y);
  300. auto base_x = x * sx;
  301. auto base_y = y * sy;
  302. for (int new_y = base_y; new_y < base_y + sy; new_y++) {
  303. for (int new_x = base_x; new_x < base_x + sx; new_x++) {
  304. new_bitmap->set_pixel(new_x, new_y, color);
  305. }
  306. }
  307. }
  308. }
  309. return new_bitmap;
  310. }
  311. // http://fourier.eng.hmc.edu/e161/lectures/resize/node3.html
  312. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::scaled(float sx, float sy) const
  313. {
  314. VERIFY(sx >= 0.0f && sy >= 0.0f);
  315. if (floorf(sx) == sx && floorf(sy) == sy)
  316. return scaled(static_cast<int>(sx), static_cast<int>(sy));
  317. int scaled_width = (int)ceilf(sx * (float)width());
  318. int scaled_height = (int)ceilf(sy * (float)height());
  319. auto new_bitmap = TRY(Gfx::Bitmap::create(format(), { scaled_width, scaled_height }, scale()));
  320. auto old_width = physical_width();
  321. auto old_height = physical_height();
  322. auto new_width = new_bitmap->physical_width();
  323. auto new_height = new_bitmap->physical_height();
  324. if (old_width == 1 && old_height == 1) {
  325. new_bitmap->fill(get_pixel(0, 0));
  326. return new_bitmap;
  327. }
  328. if (old_width > 1 && old_height > 1) {
  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.mixed_with(b, u);
  345. auto f = c.mixed_with(d, u);
  346. auto color = e.mixed_with(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.mixed_with(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.mixed_with(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. } else if (old_height == 1) {
  378. // Copy horizontal strip multiple times (excluding last pixel to out of bounds).
  379. auto old_bottom_y = old_height - 1;
  380. for (int x = 0; x < new_width - 1; x++) {
  381. auto p = static_cast<float>(x) * static_cast<float>(old_width - 1) / static_cast<float>(new_width - 1);
  382. int i = floorf(p);
  383. float u = p - static_cast<float>(i);
  384. auto a = get_pixel(i, old_bottom_y);
  385. auto b = get_pixel(i + 1, old_bottom_y);
  386. auto color = a.mixed_with(b, u);
  387. for (int new_bottom_y = 0; new_bottom_y < new_height; new_bottom_y++) {
  388. // Interpolate color only once and then copy into all columns.
  389. new_bitmap->set_pixel(x, new_bottom_y, color);
  390. }
  391. }
  392. for (int new_bottom_y = 0; new_bottom_y < new_height; new_bottom_y++) {
  393. // Copy last pixel of horizontal strip
  394. new_bitmap->set_pixel(new_width - 1, new_bottom_y, get_pixel(physical_width() - 1, old_bottom_y));
  395. }
  396. return new_bitmap;
  397. } else if (old_width == 1) {
  398. // Copy vertical strip multiple times (excluding last pixel to avoid out of bounds).
  399. auto old_right_x = old_width - 1;
  400. for (int y = 0; y < new_height - 1; y++) {
  401. auto q = static_cast<float>(y) * static_cast<float>(old_height - 1) / static_cast<float>(new_height - 1);
  402. int j = floorf(q);
  403. float v = q - static_cast<float>(j);
  404. auto c = get_pixel(old_right_x, j);
  405. auto d = get_pixel(old_right_x, j + 1);
  406. auto color = c.mixed_with(d, v);
  407. for (int new_right_x = 0; new_right_x < new_width; new_right_x++) {
  408. // Interpolate color only once and copy into all rows.
  409. new_bitmap->set_pixel(new_right_x, y, color);
  410. }
  411. }
  412. for (int new_right_x = 0; new_right_x < new_width; new_right_x++) {
  413. // Copy last pixel of vertical strip
  414. new_bitmap->set_pixel(new_right_x, new_height - 1, get_pixel(old_right_x, physical_height() - 1));
  415. }
  416. }
  417. return new_bitmap;
  418. }
  419. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::cropped(Gfx::IntRect crop, Optional<BitmapFormat> new_bitmap_format) const
  420. {
  421. auto new_bitmap = TRY(Gfx::Bitmap::create(new_bitmap_format.value_or(format()), { crop.width(), crop.height() }, scale()));
  422. auto scaled_crop = crop * scale();
  423. for (int y = 0; y < scaled_crop.height(); ++y) {
  424. for (int x = 0; x < scaled_crop.width(); ++x) {
  425. int global_x = x + scaled_crop.left();
  426. int global_y = y + scaled_crop.top();
  427. if (global_x >= physical_width() || global_y >= physical_height() || global_x < 0 || global_y < 0) {
  428. new_bitmap->set_pixel(x, y, Gfx::Color::Black);
  429. } else {
  430. new_bitmap->set_pixel(x, y, get_pixel(global_x, global_y));
  431. }
  432. }
  433. }
  434. return new_bitmap;
  435. }
  436. ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::to_bitmap_backed_by_anonymous_buffer() const
  437. {
  438. if (m_buffer.is_valid()) {
  439. // FIXME: The const_cast here is awkward.
  440. return NonnullRefPtr { const_cast<Bitmap&>(*this) };
  441. }
  442. auto buffer = TRY(Core::AnonymousBuffer::create_with_size(round_up_to_power_of_two(size_in_bytes(), PAGE_SIZE)));
  443. auto bitmap = TRY(Bitmap::create_with_anonymous_buffer(m_format, move(buffer), size(), scale(), palette_to_vector()));
  444. memcpy(bitmap->scanline(0), scanline(0), size_in_bytes());
  445. return bitmap;
  446. }
  447. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Bitmap::inverted() const
  448. {
  449. auto inverted_bitmap = TRY(clone());
  450. for (auto y = 0; y < height(); y++) {
  451. for (auto x = 0; x < width(); x++)
  452. inverted_bitmap->set_pixel(x, y, get_pixel(x, y).inverted());
  453. }
  454. return inverted_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::strip_alpha_channel()
  466. {
  467. VERIFY(m_format == BitmapFormat::BGRA8888 || m_format == BitmapFormat::BGRx8888);
  468. for (ARGB32& pixel : *this)
  469. pixel = 0xff000000 | (pixel & 0xffffff);
  470. m_format = BitmapFormat::BGRx8888;
  471. }
  472. void Bitmap::set_mmap_name([[maybe_unused]] DeprecatedString const& name)
  473. {
  474. VERIFY(m_needs_munmap);
  475. #ifdef AK_OS_SERENITY
  476. ::set_mmap_name(m_data, size_in_bytes(), name.characters());
  477. #endif
  478. }
  479. void Bitmap::fill(Color color)
  480. {
  481. VERIFY(!is_indexed(m_format));
  482. for (int y = 0; y < physical_height(); ++y) {
  483. auto* scanline = this->scanline(y);
  484. fast_u32_fill(scanline, color.value(), physical_width());
  485. }
  486. }
  487. void Bitmap::set_volatile()
  488. {
  489. if (m_volatile)
  490. return;
  491. #ifdef AK_OS_SERENITY
  492. int rc = madvise(m_data, size_in_bytes(), MADV_SET_VOLATILE);
  493. if (rc < 0) {
  494. perror("madvise(MADV_SET_VOLATILE)");
  495. VERIFY_NOT_REACHED();
  496. }
  497. #endif
  498. m_volatile = true;
  499. }
  500. [[nodiscard]] bool Bitmap::set_nonvolatile(bool& was_purged)
  501. {
  502. if (!m_volatile) {
  503. was_purged = false;
  504. return true;
  505. }
  506. #ifdef AK_OS_SERENITY
  507. int rc = madvise(m_data, size_in_bytes(), MADV_SET_NONVOLATILE);
  508. if (rc < 0) {
  509. if (errno == ENOMEM) {
  510. was_purged = true;
  511. return false;
  512. }
  513. perror("madvise(MADV_SET_NONVOLATILE)");
  514. VERIFY_NOT_REACHED();
  515. }
  516. was_purged = rc != 0;
  517. #endif
  518. m_volatile = false;
  519. return true;
  520. }
  521. Gfx::ShareableBitmap Bitmap::to_shareable_bitmap() const
  522. {
  523. auto bitmap_or_error = to_bitmap_backed_by_anonymous_buffer();
  524. if (bitmap_or_error.is_error())
  525. return {};
  526. return Gfx::ShareableBitmap { bitmap_or_error.release_value_but_fixme_should_propagate_errors(), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  527. }
  528. ErrorOr<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, IntSize size, int scale_factor)
  529. {
  530. if (size_would_overflow(format, size, scale_factor))
  531. return Error::from_string_literal("Gfx::Bitmap backing store size overflow");
  532. auto const pitch = minimum_pitch(size.width() * scale_factor, format);
  533. auto const data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  534. int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  535. #ifdef AK_OS_SERENITY
  536. map_flags |= MAP_PURGEABLE;
  537. void* data = mmap_with_name(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0, DeprecatedString::formatted("GraphicsBitmap [{}]", size).characters());
  538. #else
  539. void* data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, -1, 0);
  540. #endif
  541. if (data == MAP_FAILED)
  542. return Error::from_errno(errno);
  543. return BackingStore { data, pitch, data_size_in_bytes };
  544. }
  545. void Bitmap::allocate_palette_from_format(BitmapFormat format, Vector<ARGB32> const& source_palette)
  546. {
  547. size_t size = palette_size(format);
  548. if (size == 0)
  549. return;
  550. m_palette = new ARGB32[size];
  551. if (!source_palette.is_empty()) {
  552. VERIFY(source_palette.size() == size);
  553. memcpy(m_palette, source_palette.data(), size * sizeof(ARGB32));
  554. }
  555. }
  556. Vector<ARGB32> Bitmap::palette_to_vector() const
  557. {
  558. Vector<ARGB32> vector;
  559. auto size = palette_size(m_format);
  560. vector.ensure_capacity(size);
  561. for (size_t i = 0; i < size; ++i)
  562. vector.unchecked_append(palette_color(i).value());
  563. return vector;
  564. }
  565. bool Bitmap::visually_equals(Bitmap const& other) const
  566. {
  567. auto own_width = width();
  568. auto own_height = height();
  569. if (other.width() != own_width || other.height() != own_height)
  570. return false;
  571. for (auto y = 0; y < own_height; ++y) {
  572. for (auto x = 0; x < own_width; ++x) {
  573. if (get_pixel(x, y) != other.get_pixel(x, y))
  574. return false;
  575. }
  576. }
  577. return true;
  578. }
  579. Optional<Color> Bitmap::solid_color(u8 alpha_threshold) const
  580. {
  581. Optional<Color> color;
  582. for (auto y = 0; y < height(); ++y) {
  583. for (auto x = 0; x < width(); ++x) {
  584. auto const& pixel = get_pixel(x, y);
  585. if (has_alpha_channel() && pixel.alpha() <= alpha_threshold)
  586. continue;
  587. if (!color.has_value())
  588. color = pixel;
  589. else if (pixel != color)
  590. return {};
  591. }
  592. }
  593. return color;
  594. }
  595. void Bitmap::flood_visit_from_point(Gfx::IntPoint start_point, int threshold,
  596. Function<void(Gfx::IntPoint location)> pixel_reached)
  597. {
  598. VERIFY(rect().contains(start_point));
  599. auto target_color = get_pixel(start_point.x(), start_point.y());
  600. float threshold_normalized_squared = (threshold / 100.0f) * (threshold / 100.0f);
  601. Queue<Gfx::IntPoint> points_to_visit = Queue<Gfx::IntPoint>();
  602. points_to_visit.enqueue(start_point);
  603. pixel_reached(start_point);
  604. auto flood_mask = AK::Bitmap::create(width() * height(), false).release_value_but_fixme_should_propagate_errors();
  605. flood_mask.set(width() * start_point.y() + start_point.x(), true);
  606. // This implements a non-recursive flood fill. This is a breadth-first search of paintable neighbors
  607. // As we find neighbors that are reachable we call the location_reached callback, add them to the queue, and mark them in the mask
  608. while (!points_to_visit.is_empty()) {
  609. auto current_point = points_to_visit.dequeue();
  610. auto candidate_points = Array {
  611. current_point.moved_left(1),
  612. current_point.moved_right(1),
  613. current_point.moved_up(1),
  614. current_point.moved_down(1)
  615. };
  616. for (auto candidate_point : candidate_points) {
  617. auto flood_mask_index = width() * candidate_point.y() + candidate_point.x();
  618. if (!rect().contains(candidate_point))
  619. continue;
  620. auto pixel_color = get_pixel<Gfx::StorageFormat::BGRA8888>(candidate_point.x(), candidate_point.y());
  621. auto can_paint = pixel_color.distance_squared_to(target_color) <= threshold_normalized_squared;
  622. if (flood_mask.get(flood_mask_index) == false && can_paint) {
  623. points_to_visit.enqueue(candidate_point);
  624. pixel_reached(candidate_point);
  625. }
  626. flood_mask.set(flood_mask_index, true);
  627. }
  628. }
  629. }
  630. }