Painter.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  4. * Copyright (c) 2021, Mustafa Quraish <mustafa@serenityos.org>
  5. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  6. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  7. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  8. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  9. *
  10. * SPDX-License-Identifier: BSD-2-Clause
  11. */
  12. #include "Painter.h"
  13. #include "Bitmap.h"
  14. #include "Font/Emoji.h"
  15. #include "Font/Font.h"
  16. #include <AK/Assertions.h>
  17. #include <AK/Debug.h>
  18. #include <AK/Function.h>
  19. #include <AK/Math.h>
  20. #include <AK/Memory.h>
  21. #include <AK/Queue.h>
  22. #include <AK/QuickSort.h>
  23. #include <AK/Stack.h>
  24. #include <AK/StdLibExtras.h>
  25. #include <AK/StringBuilder.h>
  26. #include <AK/Utf8View.h>
  27. #include <LibGfx/CharacterBitmap.h>
  28. #include <LibGfx/Palette.h>
  29. #include <LibGfx/Path.h>
  30. #include <LibGfx/Quad.h>
  31. #include <LibGfx/TextDirection.h>
  32. #include <LibGfx/TextLayout.h>
  33. #include <LibUnicode/CharacterTypes.h>
  34. #include <LibUnicode/Emoji.h>
  35. #include <stdio.h>
  36. #if defined(AK_COMPILER_GCC)
  37. # pragma GCC optimize("O3")
  38. #endif
  39. namespace Gfx {
  40. template<BitmapFormat format = BitmapFormat::Invalid>
  41. ALWAYS_INLINE Color get_pixel(Gfx::Bitmap const& bitmap, int x, int y)
  42. {
  43. if constexpr (format == BitmapFormat::BGRx8888)
  44. return Color::from_rgb(bitmap.scanline(y)[x]);
  45. if constexpr (format == BitmapFormat::BGRA8888)
  46. return Color::from_argb(bitmap.scanline(y)[x]);
  47. return bitmap.get_pixel(x, y);
  48. }
  49. Painter::Painter(Gfx::Bitmap& bitmap)
  50. : m_target(bitmap)
  51. {
  52. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRx8888 || bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  53. m_state_stack.append(State());
  54. state().clip_rect = { { 0, 0 }, bitmap.size() };
  55. m_clip_origin = state().clip_rect;
  56. }
  57. void Painter::clear_rect(IntRect const& a_rect, Color color)
  58. {
  59. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  60. if (rect.is_empty())
  61. return;
  62. VERIFY(target().rect().contains(rect));
  63. ARGB32* dst = target().scanline(rect.top()) + rect.left();
  64. size_t const dst_skip = target().pitch() / sizeof(ARGB32);
  65. for (int i = rect.height() - 1; i >= 0; --i) {
  66. fast_u32_fill(dst, color.value(), rect.width());
  67. dst += dst_skip;
  68. }
  69. }
  70. void Painter::fill_physical_rect(IntRect const& physical_rect, Color color)
  71. {
  72. // Callers must do clipping.
  73. ARGB32* dst = target().scanline(physical_rect.top()) + physical_rect.left();
  74. size_t const dst_skip = target().pitch() / sizeof(ARGB32);
  75. auto dst_format = target().format();
  76. for (int i = physical_rect.height() - 1; i >= 0; --i) {
  77. for (int j = 0; j < physical_rect.width(); ++j)
  78. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  79. dst += dst_skip;
  80. }
  81. }
  82. void Painter::fill_rect(IntRect const& a_rect, Color color)
  83. {
  84. if (color.alpha() == 0)
  85. return;
  86. if (color.alpha() == 0xff) {
  87. clear_rect(a_rect, color);
  88. return;
  89. }
  90. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  91. if (rect.is_empty())
  92. return;
  93. VERIFY(target().rect().contains(rect));
  94. fill_physical_rect(rect, color);
  95. }
  96. void Painter::fill_rect(IntRect const& rect, PaintStyle const& paint_style)
  97. {
  98. auto a_rect = rect.translated(translation());
  99. auto clipped_rect = a_rect.intersected(clip_rect());
  100. if (clipped_rect.is_empty())
  101. return;
  102. auto start_offset = clipped_rect.location() - a_rect.location();
  103. paint_style.paint(a_rect, [&](PaintStyle::SamplerFunction sample) {
  104. for (int y = 0; y < clipped_rect.height(); ++y) {
  105. for (int x = 0; x < clipped_rect.width(); ++x) {
  106. IntPoint point(x, y);
  107. set_physical_pixel(point + clipped_rect.location(), sample(point + start_offset), true);
  108. }
  109. }
  110. });
  111. }
  112. void Painter::fill_rect_with_gradient(Orientation orientation, IntRect const& a_rect, Color gradient_start, Color gradient_end)
  113. {
  114. if (gradient_start == gradient_end) {
  115. fill_rect(a_rect, gradient_start);
  116. return;
  117. }
  118. return fill_rect_with_linear_gradient(a_rect, Array { ColorStop { gradient_start, 0 }, ColorStop { gradient_end, 1 } }, orientation == Orientation::Horizontal ? 90.0f : 0.0f);
  119. }
  120. void Painter::fill_rect_with_gradient(IntRect const& a_rect, Color gradient_start, Color gradient_end)
  121. {
  122. return fill_rect_with_gradient(Orientation::Horizontal, a_rect, gradient_start, gradient_end);
  123. }
  124. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  125. {
  126. return fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  127. }
  128. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius)
  129. {
  130. // Fasttrack for rects without any border radii
  131. if (!top_left_radius && !top_right_radius && !bottom_right_radius && !bottom_left_radius)
  132. return fill_rect(a_rect, color);
  133. // Fully transparent, dont care.
  134. if (color.alpha() == 0)
  135. return;
  136. // FIXME: Allow for elliptically rounded corners
  137. IntRect top_left_corner = {
  138. a_rect.x(),
  139. a_rect.y(),
  140. top_left_radius,
  141. top_left_radius
  142. };
  143. IntRect top_right_corner = {
  144. a_rect.x() + a_rect.width() - top_right_radius,
  145. a_rect.y(),
  146. top_right_radius,
  147. top_right_radius
  148. };
  149. IntRect bottom_right_corner = {
  150. a_rect.x() + a_rect.width() - bottom_right_radius,
  151. a_rect.y() + a_rect.height() - bottom_right_radius,
  152. bottom_right_radius,
  153. bottom_right_radius
  154. };
  155. IntRect bottom_left_corner = {
  156. a_rect.x(),
  157. a_rect.y() + a_rect.height() - bottom_left_radius,
  158. bottom_left_radius,
  159. bottom_left_radius
  160. };
  161. IntRect top_rect = {
  162. a_rect.x() + top_left_radius,
  163. a_rect.y(),
  164. a_rect.width() - top_left_radius - top_right_radius, top_left_radius
  165. };
  166. IntRect right_rect = {
  167. a_rect.x() + a_rect.width() - top_right_radius,
  168. a_rect.y() + top_right_radius,
  169. top_right_radius,
  170. a_rect.height() - top_right_radius - bottom_right_radius
  171. };
  172. IntRect bottom_rect = {
  173. a_rect.x() + bottom_left_radius,
  174. a_rect.y() + a_rect.height() - bottom_right_radius,
  175. a_rect.width() - bottom_left_radius - bottom_right_radius,
  176. bottom_right_radius
  177. };
  178. IntRect left_rect = {
  179. a_rect.x(),
  180. a_rect.y() + top_left_radius,
  181. bottom_left_radius,
  182. a_rect.height() - top_left_radius - bottom_left_radius
  183. };
  184. IntRect inner = {
  185. left_rect.x() + left_rect.width(),
  186. left_rect.y(),
  187. a_rect.width() - left_rect.width() - right_rect.width(),
  188. a_rect.height() - top_rect.height() - bottom_rect.height()
  189. };
  190. fill_rect(top_rect, color);
  191. fill_rect(right_rect, color);
  192. fill_rect(bottom_rect, color);
  193. fill_rect(left_rect, color);
  194. fill_rect(inner, color);
  195. if (top_left_radius)
  196. fill_rounded_corner(top_left_corner, top_left_radius, color, CornerOrientation::TopLeft);
  197. if (top_right_radius)
  198. fill_rounded_corner(top_right_corner, top_right_radius, color, CornerOrientation::TopRight);
  199. if (bottom_left_radius)
  200. fill_rounded_corner(bottom_left_corner, bottom_left_radius, color, CornerOrientation::BottomLeft);
  201. if (bottom_right_radius)
  202. fill_rounded_corner(bottom_right_corner, bottom_right_radius, color, CornerOrientation::BottomRight);
  203. }
  204. void Painter::fill_rounded_corner(IntRect const& a_rect, int radius, Color color, CornerOrientation orientation)
  205. {
  206. // Care about clipping
  207. auto translated_a_rect = a_rect.translated(translation());
  208. auto rect = translated_a_rect.intersected(clip_rect());
  209. if (rect.is_empty())
  210. return;
  211. VERIFY(target().rect().contains(rect));
  212. // We got cut on the top!
  213. // FIXME: Also account for clipping on the x-axis
  214. int clip_offset = 0;
  215. if (translated_a_rect.y() < rect.y())
  216. clip_offset = rect.y() - translated_a_rect.y();
  217. ARGB32* dst = target().scanline(rect.top()) + rect.left();
  218. size_t const dst_skip = target().pitch() / sizeof(ARGB32);
  219. IntPoint circle_center;
  220. switch (orientation) {
  221. case CornerOrientation::TopLeft:
  222. circle_center = { radius, radius + 1 };
  223. break;
  224. case CornerOrientation::TopRight:
  225. circle_center = { -1, radius + 1 };
  226. break;
  227. case CornerOrientation::BottomRight:
  228. circle_center = { -1, 0 };
  229. break;
  230. case CornerOrientation::BottomLeft:
  231. circle_center = { radius, 0 };
  232. break;
  233. default:
  234. VERIFY_NOT_REACHED();
  235. }
  236. int radius2 = radius * radius;
  237. auto is_in_circle = [&](int x, int y) {
  238. int distance2 = (circle_center.x() - x) * (circle_center.x() - x) + (circle_center.y() - y) * (circle_center.y() - y);
  239. // To reflect the grid and be compatible with the draw_circle_arc_intersecting algorithm
  240. // add 1/2 to the radius
  241. return distance2 <= (radius2 + radius + 0.25);
  242. };
  243. auto dst_format = target().format();
  244. for (int i = rect.height() - 1; i >= 0; --i) {
  245. for (int j = 0; j < rect.width(); ++j)
  246. if (is_in_circle(j, rect.height() - i + clip_offset))
  247. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  248. dst += dst_skip;
  249. }
  250. }
  251. // The callback will only be called for a quarter of the ellipse, the user is intended to deduce other points.
  252. // As the coordinate space is relative to the center of the rectangle, it's simply (x, y), (x, -y), (-x, y) and (-x, -y).
  253. static void on_each_ellipse_point(IntRect const& rect, Function<void(IntPoint)>&& callback)
  254. {
  255. // Note: This is an implementation of the Midpoint Ellipse Algorithm.
  256. double const a = rect.width() / 2;
  257. double const a_square = a * a;
  258. double const b = rect.height() / 2;
  259. double const b_square = b * b;
  260. int x = 0;
  261. auto y = static_cast<int>(b);
  262. double dx = 2 * b_square * x;
  263. double dy = 2 * a_square * y;
  264. // For region 1:
  265. auto decision_parameter = b_square - a_square * b + .25 * a_square;
  266. while (dx < dy) {
  267. callback({ x, y });
  268. if (decision_parameter >= 0) {
  269. y--;
  270. dy -= 2 * a_square;
  271. decision_parameter -= dy;
  272. }
  273. x++;
  274. dx += 2 * b_square;
  275. decision_parameter += dx + b_square;
  276. }
  277. // For region 2:
  278. decision_parameter = b_square * ((x + 0.5) * (x + 0.5)) + a_square * ((y - 1) * (y - 1)) - a_square * b_square;
  279. while (y >= 0) {
  280. callback({ x, y });
  281. if (decision_parameter <= 0) {
  282. x++;
  283. dx += 2 * b_square;
  284. decision_parameter += dx;
  285. }
  286. y--;
  287. dy -= 2 * a_square;
  288. decision_parameter += a_square - dy;
  289. }
  290. }
  291. void Painter::fill_ellipse(IntRect const& a_rect, Color color)
  292. {
  293. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  294. if (rect.is_empty())
  295. return;
  296. VERIFY(target().rect().contains(rect));
  297. auto const center = a_rect.center();
  298. on_each_ellipse_point(rect, [this, &color, center](IntPoint position) {
  299. IntPoint const directions[4] = { { position.x(), position.y() }, { -position.x(), position.y() }, { position.x(), -position.y() }, { -position.x(), -position.y() } };
  300. draw_line(center + directions[0], center + directions[1], color);
  301. draw_line(center + directions[2], center + directions[3], color);
  302. });
  303. }
  304. template<typename RectType, typename Callback>
  305. static void for_each_pixel_around_rect_clockwise(RectType const& rect, Callback callback)
  306. {
  307. if (rect.is_empty())
  308. return;
  309. for (auto x = rect.left(); x < rect.right(); ++x)
  310. callback(x, rect.top());
  311. for (auto y = rect.top() + 1; y < rect.bottom(); ++y)
  312. callback(rect.right() - 1, y);
  313. for (auto x = rect.right() - 2; x >= rect.left(); --x)
  314. callback(x, rect.bottom() - 1);
  315. for (auto y = rect.bottom() - 2; y > rect.top(); --y)
  316. callback(rect.left(), y);
  317. }
  318. void Painter::draw_rect(IntRect const& a_rect, Color color, bool rough)
  319. {
  320. IntRect rect = a_rect.translated(translation());
  321. auto clipped_rect = rect.intersected(clip_rect());
  322. if (clipped_rect.is_empty())
  323. return;
  324. int min_y = clipped_rect.top();
  325. int max_y = clipped_rect.bottom() - 1;
  326. if (rect.top() >= clipped_rect.top() && rect.top() < clipped_rect.bottom()) {
  327. int width = rough ? max(0, min(rect.width() - 2, clipped_rect.width())) : clipped_rect.width();
  328. if (width > 0) {
  329. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  330. fill_physical_scanline(rect.top(), start_x, width, color);
  331. }
  332. ++min_y;
  333. }
  334. if (rect.bottom() > clipped_rect.top() && rect.bottom() <= clipped_rect.bottom()) {
  335. int width = rough ? max(0, min(rect.width() - 2, clipped_rect.width())) : clipped_rect.width();
  336. if (width > 0) {
  337. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  338. fill_physical_scanline(max_y, start_x, width, color);
  339. }
  340. --max_y;
  341. }
  342. bool draw_left_side = rect.left() >= clipped_rect.left();
  343. bool draw_right_side = rect.right() == clipped_rect.right();
  344. if (draw_left_side && draw_right_side) {
  345. // Specialized loop when drawing both sides.
  346. for (int y = min_y; y <= max_y; ++y) {
  347. auto* bits = target().scanline(y);
  348. set_physical_pixel(bits[rect.left()], color);
  349. set_physical_pixel(bits[(rect.right() - 1)], color);
  350. }
  351. } else {
  352. for (int y = min_y; y <= max_y; ++y) {
  353. auto* bits = target().scanline(y);
  354. if (draw_left_side)
  355. set_physical_pixel(bits[rect.left()], color);
  356. if (draw_right_side)
  357. set_physical_pixel(bits[(rect.right() - 1)], color);
  358. }
  359. }
  360. }
  361. struct BlitState {
  362. enum AlphaState {
  363. NoAlpha = 0,
  364. SrcAlpha = 1,
  365. DstAlpha = 2,
  366. BothAlpha = SrcAlpha | DstAlpha
  367. };
  368. ARGB32 const* src;
  369. ARGB32* dst;
  370. size_t src_pitch;
  371. size_t dst_pitch;
  372. int row_count;
  373. int column_count;
  374. float opacity;
  375. BitmapFormat src_format;
  376. };
  377. // FIXME: This is a hack to support blit_with_opacity() with RGBA8888 source.
  378. // Ideally we'd have a more generic solution that allows any source format.
  379. static void swap_red_and_blue_channels(Color& color)
  380. {
  381. u32 rgba = color.value();
  382. u32 bgra = (rgba & 0xff00ff00)
  383. | ((rgba & 0x000000ff) << 16)
  384. | ((rgba & 0x00ff0000) >> 16);
  385. color = Color::from_argb(bgra);
  386. }
  387. // FIXME: This function is very unoptimized.
  388. template<BlitState::AlphaState has_alpha>
  389. static void do_blit_with_opacity(BlitState& state)
  390. {
  391. for (int row = 0; row < state.row_count; ++row) {
  392. for (int x = 0; x < state.column_count; ++x) {
  393. Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_argb(state.dst[x]) : Color::from_rgb(state.dst[x]);
  394. if constexpr (has_alpha & BlitState::SrcAlpha) {
  395. Color src_color_with_alpha = Color::from_argb(state.src[x]);
  396. if (state.src_format == BitmapFormat::RGBA8888)
  397. swap_red_and_blue_channels(src_color_with_alpha);
  398. float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
  399. src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
  400. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  401. } else {
  402. Color src_color_with_alpha = Color::from_rgb(state.src[x]);
  403. if (state.src_format == BitmapFormat::RGBA8888)
  404. swap_red_and_blue_channels(src_color_with_alpha);
  405. src_color_with_alpha.set_alpha(state.opacity * 255);
  406. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  407. }
  408. }
  409. state.dst += state.dst_pitch;
  410. state.src += state.src_pitch;
  411. }
  412. }
  413. void Painter::blit_with_opacity(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, float opacity, bool apply_alpha)
  414. {
  415. if (opacity >= 1.0f && !(source.has_alpha_channel() && apply_alpha))
  416. return blit(position, source, src_rect);
  417. IntRect safe_src_rect = IntRect::intersection(src_rect, source.rect());
  418. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  419. auto clipped_rect = dst_rect.intersected(clip_rect());
  420. if (clipped_rect.is_empty())
  421. return;
  422. int const first_row = clipped_rect.top() - dst_rect.top();
  423. int const last_row = clipped_rect.bottom() - dst_rect.top();
  424. int const first_column = clipped_rect.left() - dst_rect.left();
  425. int const last_column = clipped_rect.right() - dst_rect.left();
  426. BlitState blit_state {
  427. .src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column,
  428. .dst = target().scanline(clipped_rect.y()) + clipped_rect.x(),
  429. .src_pitch = source.pitch() / sizeof(ARGB32),
  430. .dst_pitch = target().pitch() / sizeof(ARGB32),
  431. .row_count = last_row - first_row,
  432. .column_count = last_column - first_column,
  433. .opacity = opacity,
  434. .src_format = source.format(),
  435. };
  436. if (source.has_alpha_channel() && apply_alpha) {
  437. if (target().has_alpha_channel())
  438. do_blit_with_opacity<BlitState::BothAlpha>(blit_state);
  439. else
  440. do_blit_with_opacity<BlitState::SrcAlpha>(blit_state);
  441. } else {
  442. if (target().has_alpha_channel())
  443. do_blit_with_opacity<BlitState::DstAlpha>(blit_state);
  444. else
  445. do_blit_with_opacity<BlitState::NoAlpha>(blit_state);
  446. }
  447. }
  448. void Painter::blit_filtered(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, Function<Color(Color)> const& filter, bool apply_alpha)
  449. {
  450. IntRect safe_src_rect = src_rect.intersected(source.rect());
  451. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  452. auto clipped_rect = dst_rect.intersected(clip_rect());
  453. if (clipped_rect.is_empty())
  454. return;
  455. int const first_row = clipped_rect.top() - dst_rect.top();
  456. int const last_row = clipped_rect.bottom() - dst_rect.top();
  457. int const first_column = clipped_rect.left() - dst_rect.left();
  458. int const last_column = clipped_rect.right() - dst_rect.left();
  459. ARGB32* dst = target().scanline(clipped_rect.y()) + clipped_rect.x();
  460. size_t const dst_skip = target().pitch() / sizeof(ARGB32);
  461. auto dst_format = target().format();
  462. auto src_format = source.format();
  463. ARGB32 const* src = source.scanline(safe_src_rect.top() + first_row) + safe_src_rect.left() + first_column;
  464. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  465. for (int row = first_row; row < last_row; ++row) {
  466. for (int x = 0; x < (last_column - first_column); ++x) {
  467. auto source_color = color_for_format(src_format, src[x]);
  468. if (source_color.alpha() == 0)
  469. continue;
  470. auto filtered_color = filter(source_color);
  471. if (!apply_alpha || filtered_color.alpha() == 0xff)
  472. dst[x] = filtered_color.value();
  473. else
  474. dst[x] = color_for_format(dst_format, dst[x]).blend(filtered_color).value();
  475. }
  476. dst += dst_skip;
  477. src += src_skip;
  478. }
  479. }
  480. void Painter::blit(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, float opacity, bool apply_alpha)
  481. {
  482. if (opacity < 1.0f || (source.has_alpha_channel() && apply_alpha))
  483. return blit_with_opacity(position, source, src_rect, opacity, apply_alpha);
  484. auto safe_src_rect = src_rect.intersected(source.rect());
  485. // If we get here, the Painter might have a scale factor, but the source bitmap has the same scale factor.
  486. // We need to transform from logical to physical coordinates, but we can just copy pixels without resampling.
  487. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  488. auto clipped_rect = dst_rect.intersected(clip_rect());
  489. if (clipped_rect.is_empty())
  490. return;
  491. int const first_row = clipped_rect.top() - dst_rect.top();
  492. int const last_row = clipped_rect.bottom() - dst_rect.top();
  493. int const first_column = clipped_rect.left() - dst_rect.left();
  494. ARGB32* dst = target().scanline(clipped_rect.y()) + clipped_rect.x();
  495. size_t const dst_skip = target().pitch() / sizeof(ARGB32);
  496. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  497. ARGB32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  498. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  499. for (int row = first_row; row < last_row; ++row) {
  500. memcpy(dst, src, sizeof(ARGB32) * clipped_rect.width());
  501. dst += dst_skip;
  502. src += src_skip;
  503. }
  504. return;
  505. }
  506. if (source.format() == BitmapFormat::RGBA8888) {
  507. u32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  508. size_t const src_skip = source.pitch() / sizeof(u32);
  509. for (int row = first_row; row < last_row; ++row) {
  510. for (int i = 0; i < clipped_rect.width(); ++i) {
  511. u32 rgba = src[i];
  512. u32 bgra = (rgba & 0xff00ff00)
  513. | ((rgba & 0x000000ff) << 16)
  514. | ((rgba & 0x00ff0000) >> 16);
  515. dst[i] = bgra;
  516. }
  517. dst += dst_skip;
  518. src += src_skip;
  519. }
  520. return;
  521. }
  522. VERIFY_NOT_REACHED();
  523. }
  524. template<bool has_alpha_channel, typename GetPixel>
  525. ALWAYS_INLINE static void do_draw_integer_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& src_rect, Gfx::Bitmap const& source, int hfactor, int vfactor, GetPixel get_pixel, float opacity)
  526. {
  527. bool has_opacity = opacity != 1.0f;
  528. for (int y = 0; y < src_rect.height(); ++y) {
  529. int dst_y = dst_rect.y() + y * vfactor;
  530. for (int x = 0; x < src_rect.width(); ++x) {
  531. auto src_pixel = get_pixel(source, x + src_rect.left(), y + src_rect.top());
  532. if (has_opacity)
  533. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  534. for (int yo = 0; yo < vfactor; ++yo) {
  535. auto* scanline = (Color*)target.scanline(dst_y + yo);
  536. int dst_x = dst_rect.x() + x * hfactor;
  537. for (int xo = 0; xo < hfactor; ++xo) {
  538. if constexpr (has_alpha_channel)
  539. scanline[dst_x + xo] = scanline[dst_x + xo].blend(src_pixel);
  540. else
  541. scanline[dst_x + xo] = src_pixel;
  542. }
  543. }
  544. }
  545. }
  546. }
  547. template<bool has_alpha_channel, typename GetPixel>
  548. ALWAYS_INLINE static void do_draw_box_sampled_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity)
  549. {
  550. float source_pixel_width = src_rect.width() / dst_rect.width();
  551. float source_pixel_height = src_rect.height() / dst_rect.height();
  552. float source_pixel_area = source_pixel_width * source_pixel_height;
  553. FloatRect const pixel_box = { 0.f, 0.f, 1.f, 1.f };
  554. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  555. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  556. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  557. // Project the destination pixel in the source image
  558. FloatRect const source_box = {
  559. src_rect.left() + (x - dst_rect.x()) * source_pixel_width,
  560. src_rect.top() + (y - dst_rect.y()) * source_pixel_height,
  561. source_pixel_width,
  562. source_pixel_height,
  563. };
  564. IntRect enclosing_source_box = enclosing_int_rect(source_box).intersected(source.rect());
  565. // Sum the contribution of all source pixels inside the projected pixel
  566. float red_accumulator = 0.f;
  567. float green_accumulator = 0.f;
  568. float blue_accumulator = 0.f;
  569. float total_area = 0.f;
  570. for (int sy = enclosing_source_box.y(); sy < enclosing_source_box.bottom(); ++sy) {
  571. for (int sx = enclosing_source_box.x(); sx < enclosing_source_box.right(); ++sx) {
  572. float area = source_box.intersected(pixel_box.translated(sx, sy)).size().area();
  573. auto pixel = get_pixel(source, sx, sy);
  574. area *= pixel.alpha() / 255.f;
  575. red_accumulator += pixel.red() * area;
  576. green_accumulator += pixel.green() * area;
  577. blue_accumulator += pixel.blue() * area;
  578. total_area += area;
  579. }
  580. }
  581. Color src_pixel = {
  582. round_to<u8>(min(red_accumulator / total_area, 255.f)),
  583. round_to<u8>(min(green_accumulator / total_area, 255.f)),
  584. round_to<u8>(min(blue_accumulator / total_area, 255.f)),
  585. round_to<u8>(min(total_area * 255.f / source_pixel_area * opacity, 255.f)),
  586. };
  587. if constexpr (has_alpha_channel)
  588. scanline[x] = scanline[x].blend(src_pixel);
  589. else
  590. scanline[x] = src_pixel;
  591. }
  592. }
  593. }
  594. template<bool has_alpha_channel, ScalingMode scaling_mode, typename GetPixel>
  595. ALWAYS_INLINE static void do_draw_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity)
  596. {
  597. auto int_src_rect = enclosing_int_rect(src_rect);
  598. auto clipped_src_rect = int_src_rect.intersected(source.rect());
  599. if (clipped_src_rect.is_empty())
  600. return;
  601. if constexpr (scaling_mode == ScalingMode::NearestNeighbor || scaling_mode == ScalingMode::SmoothPixels) {
  602. if (dst_rect == clipped_rect && int_src_rect == src_rect && !(dst_rect.width() % int_src_rect.width()) && !(dst_rect.height() % int_src_rect.height())) {
  603. int hfactor = dst_rect.width() / int_src_rect.width();
  604. int vfactor = dst_rect.height() / int_src_rect.height();
  605. if (hfactor == 2 && vfactor == 2)
  606. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 2, 2, get_pixel, opacity);
  607. if (hfactor == 3 && vfactor == 3)
  608. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 3, 3, get_pixel, opacity);
  609. if (hfactor == 4 && vfactor == 4)
  610. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 4, 4, get_pixel, opacity);
  611. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  612. }
  613. }
  614. if constexpr (scaling_mode == ScalingMode::BoxSampling)
  615. return do_draw_box_sampled_scaled_bitmap<has_alpha_channel>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  616. bool has_opacity = opacity != 1.f;
  617. i64 shift = 1ll << 32;
  618. i64 fractional_mask = shift - 1;
  619. i64 bilinear_offset_x = (1ll << 31) * (src_rect.width() / dst_rect.width() - 1);
  620. i64 bilinear_offset_y = (1ll << 31) * (src_rect.height() / dst_rect.height() - 1);
  621. i64 hscale = src_rect.width() * shift / dst_rect.width();
  622. i64 vscale = src_rect.height() * shift / dst_rect.height();
  623. i64 src_left = src_rect.left() * shift;
  624. i64 src_top = src_rect.top() * shift;
  625. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  626. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  627. auto desired_y = (y - dst_rect.y()) * vscale + src_top;
  628. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  629. auto desired_x = (x - dst_rect.x()) * hscale + src_left;
  630. Color src_pixel;
  631. if constexpr (scaling_mode == ScalingMode::BilinearBlend) {
  632. auto shifted_x = desired_x + bilinear_offset_x;
  633. auto shifted_y = desired_y + bilinear_offset_y;
  634. auto scaled_x0 = clamp(shifted_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  635. auto scaled_x1 = clamp((shifted_x >> 32) + 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  636. auto scaled_y0 = clamp(shifted_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  637. auto scaled_y1 = clamp((shifted_y >> 32) + 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  638. float x_ratio = (shifted_x & fractional_mask) / static_cast<float>(shift);
  639. float y_ratio = (shifted_y & fractional_mask) / static_cast<float>(shift);
  640. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  641. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  642. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  643. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  644. auto top = top_left.mixed_with(top_right, x_ratio);
  645. auto bottom = bottom_left.mixed_with(bottom_right, x_ratio);
  646. src_pixel = top.mixed_with(bottom, y_ratio);
  647. } else if constexpr (scaling_mode == ScalingMode::SmoothPixels) {
  648. auto scaled_x1 = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  649. auto scaled_x0 = clamp(scaled_x1 - 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  650. auto scaled_y1 = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  651. auto scaled_y0 = clamp(scaled_y1 - 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  652. float x_ratio = (desired_x & fractional_mask) / (float)shift;
  653. float y_ratio = (desired_y & fractional_mask) / (float)shift;
  654. float scaled_x_ratio = clamp(x_ratio * dst_rect.width() / (float)src_rect.width(), 0.f, 1.f);
  655. float scaled_y_ratio = clamp(y_ratio * dst_rect.height() / (float)src_rect.height(), 0.f, 1.f);
  656. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  657. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  658. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  659. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  660. auto top = top_left.mixed_with(top_right, scaled_x_ratio);
  661. auto bottom = bottom_left.mixed_with(bottom_right, scaled_x_ratio);
  662. src_pixel = top.mixed_with(bottom, scaled_y_ratio);
  663. } else {
  664. auto scaled_x = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  665. auto scaled_y = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  666. src_pixel = get_pixel(source, scaled_x, scaled_y);
  667. }
  668. if (has_opacity)
  669. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  670. if constexpr (has_alpha_channel)
  671. scanline[x] = scanline[x].blend(src_pixel);
  672. else
  673. scanline[x] = src_pixel;
  674. }
  675. }
  676. }
  677. template<bool has_alpha_channel, typename GetPixel>
  678. ALWAYS_INLINE static void do_draw_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity, ScalingMode scaling_mode)
  679. {
  680. switch (scaling_mode) {
  681. case ScalingMode::NearestNeighbor:
  682. do_draw_scaled_bitmap<has_alpha_channel, ScalingMode::NearestNeighbor>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  683. break;
  684. case ScalingMode::SmoothPixels:
  685. do_draw_scaled_bitmap<has_alpha_channel, ScalingMode::SmoothPixels>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  686. break;
  687. case ScalingMode::BilinearBlend:
  688. do_draw_scaled_bitmap<has_alpha_channel, ScalingMode::BilinearBlend>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  689. break;
  690. case ScalingMode::BoxSampling:
  691. do_draw_scaled_bitmap<has_alpha_channel, ScalingMode::BoxSampling>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  692. break;
  693. case ScalingMode::None:
  694. do_draw_scaled_bitmap<has_alpha_channel, ScalingMode::None>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  695. break;
  696. }
  697. }
  698. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  699. {
  700. draw_scaled_bitmap(a_dst_rect, source, FloatRect { a_src_rect }, opacity, scaling_mode);
  701. }
  702. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, FloatRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  703. {
  704. IntRect int_src_rect = enclosing_int_rect(a_src_rect);
  705. if (a_src_rect == int_src_rect && a_dst_rect.size() == int_src_rect.size())
  706. return blit(a_dst_rect.location(), source, int_src_rect, opacity);
  707. if (scaling_mode == ScalingMode::None) {
  708. IntRect clipped_draw_rect { (int)a_src_rect.location().x(), (int)a_src_rect.location().y(), a_dst_rect.size().width(), a_dst_rect.size().height() };
  709. return blit(a_dst_rect.location(), source, clipped_draw_rect, opacity);
  710. }
  711. auto dst_rect = to_physical(a_dst_rect);
  712. auto src_rect = a_src_rect;
  713. auto clipped_rect = dst_rect.intersected(clip_rect());
  714. if (clipped_rect.is_empty())
  715. return;
  716. if (source.has_alpha_channel() || opacity != 1.0f) {
  717. switch (source.format()) {
  718. case BitmapFormat::BGRx8888:
  719. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  720. break;
  721. case BitmapFormat::BGRA8888:
  722. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRA8888>, opacity, scaling_mode);
  723. break;
  724. default:
  725. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  726. break;
  727. }
  728. } else {
  729. switch (source.format()) {
  730. case BitmapFormat::BGRx8888:
  731. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  732. break;
  733. default:
  734. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  735. break;
  736. }
  737. }
  738. }
  739. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Font const& font, Color color)
  740. {
  741. auto top_left = point + FloatPoint(font.glyph_left_bearing(code_point), 0);
  742. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  743. auto glyph = font.glyph(code_point, glyph_position.subpixel_offset);
  744. if (glyph.is_color_bitmap()) {
  745. float scaled_width = glyph.advance();
  746. float ratio = static_cast<float>(glyph.bitmap()->height()) / static_cast<float>(glyph.bitmap()->width());
  747. float scaled_height = scaled_width * ratio;
  748. FloatRect rect(point.x(), point.y(), scaled_width, scaled_height);
  749. draw_scaled_bitmap(rect.to_rounded<int>(), *glyph.bitmap(), glyph.bitmap()->rect(), 1.0f, ScalingMode::BilinearBlend);
  750. } else if (color.alpha() != 255) {
  751. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  752. return pixel.multiply(color);
  753. });
  754. } else {
  755. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  756. return color.with_alpha(pixel.alpha());
  757. });
  758. }
  759. }
  760. void Painter::draw_emoji(IntPoint point, Gfx::Bitmap const& emoji, Font const& font)
  761. {
  762. IntRect dst_rect {
  763. point.x(),
  764. point.y(),
  765. font.pixel_size_rounded_up() * emoji.width() / emoji.height(),
  766. font.pixel_size_rounded_up(),
  767. };
  768. draw_scaled_bitmap(dst_rect, emoji, emoji.rect());
  769. }
  770. void Painter::draw_glyph_or_emoji(FloatPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  771. {
  772. auto draw_glyph_or_emoji = prepare_draw_glyph_or_emoji(point, it, font);
  773. if (draw_glyph_or_emoji.has<DrawGlyph>()) {
  774. auto& glyph = draw_glyph_or_emoji.get<DrawGlyph>();
  775. draw_glyph(glyph.position, glyph.code_point, *glyph.font, color);
  776. } else {
  777. auto& emoji = draw_glyph_or_emoji.get<DrawEmoji>();
  778. draw_emoji(emoji.position.to_type<int>(), *emoji.emoji, *emoji.font);
  779. }
  780. }
  781. template<typename DrawGlyphFunction>
  782. void draw_text_line(FloatRect const& a_rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextDirection direction, DrawGlyphFunction draw_glyph)
  783. {
  784. auto rect = a_rect;
  785. switch (alignment) {
  786. case TextAlignment::TopLeft:
  787. case TextAlignment::CenterLeft:
  788. case TextAlignment::BottomLeft:
  789. break;
  790. case TextAlignment::TopRight:
  791. case TextAlignment::CenterRight:
  792. case TextAlignment::BottomRight:
  793. rect.set_x(rect.right() - 1 - font.width(text));
  794. break;
  795. case TextAlignment::TopCenter:
  796. case TextAlignment::BottomCenter:
  797. case TextAlignment::Center: {
  798. auto shrunken_rect = rect;
  799. shrunken_rect.set_width(font.width(text));
  800. shrunken_rect.center_within(rect);
  801. rect = shrunken_rect;
  802. break;
  803. }
  804. default:
  805. VERIFY_NOT_REACHED();
  806. }
  807. auto point = rect.location();
  808. auto space_width = font.glyph_width(' ');
  809. if (direction == TextDirection::RTL) {
  810. point.translate_by(rect.width(), 0); // Start drawing from the end
  811. space_width = -space_width; // Draw spaces backwards
  812. }
  813. u32 last_code_point { 0 };
  814. for (auto it = text.begin(); it != text.end(); ++it) {
  815. auto code_point = *it;
  816. if (should_paint_as_space(code_point)) {
  817. point.translate_by(space_width, 0);
  818. last_code_point = code_point;
  819. continue;
  820. }
  821. auto kerning = font.glyphs_horizontal_kerning(last_code_point, code_point);
  822. if (kerning != 0.0f)
  823. point.translate_by(direction == TextDirection::LTR ? kerning : -kerning, 0);
  824. auto it_copy = it; // The callback function will advance the iterator, so create a copy for this lookup.
  825. FloatSize glyph_size(font.glyph_or_emoji_width(it_copy), font.pixel_size());
  826. if (direction == TextDirection::RTL)
  827. point.translate_by(-glyph_size.width(), 0); // If we are drawing right to left, we have to move backwards before drawing the glyph
  828. draw_glyph({ point, glyph_size }, it);
  829. if (direction == TextDirection::LTR)
  830. point.translate_by(glyph_size.width(), 0);
  831. // The callback function might have exhausted the iterator.
  832. if (it == text.end())
  833. break;
  834. last_code_point = code_point;
  835. }
  836. }
  837. static inline size_t draw_text_get_length(Utf8View const& text)
  838. {
  839. return text.byte_length();
  840. }
  841. Vector<DirectionalRun> Painter::split_text_into_directional_runs(Utf8View const& text, TextDirection initial_direction)
  842. {
  843. // FIXME: This is a *very* simplified version of the UNICODE BIDIRECTIONAL ALGORITHM (https://www.unicode.org/reports/tr9/), that can render most bidirectional text
  844. // but also produces awkward results in a large amount of edge cases. This should probably be replaced with a fully spec compliant implementation at some point.
  845. // FIXME: Support HTML "dir" attribute (how?)
  846. u8 paragraph_embedding_level = initial_direction == TextDirection::LTR ? 0 : 1;
  847. Vector<u8> embedding_levels;
  848. embedding_levels.ensure_capacity(text.length());
  849. for (size_t i = 0; i < text.length(); i++)
  850. embedding_levels.unchecked_append(paragraph_embedding_level);
  851. // FIXME: Support Explicit Directional Formatting Characters
  852. Vector<BidirectionalClass> character_classes;
  853. character_classes.ensure_capacity(text.length());
  854. for (u32 code_point : text)
  855. character_classes.unchecked_append(get_char_bidi_class(code_point));
  856. // resolving weak types
  857. BidirectionalClass paragraph_class = initial_direction == TextDirection::LTR ? BidirectionalClass::STRONG_LTR : BidirectionalClass::STRONG_RTL;
  858. for (size_t i = 0; i < character_classes.size(); i++) {
  859. if (character_classes[i] != BidirectionalClass::WEAK_SEPARATORS)
  860. continue;
  861. for (ssize_t j = i - 1; j >= 0; j--) {
  862. auto character_class = character_classes[j];
  863. if (character_class != BidirectionalClass::STRONG_RTL && character_class != BidirectionalClass::STRONG_LTR)
  864. continue;
  865. character_classes[i] = character_class;
  866. break;
  867. }
  868. if (character_classes[i] == BidirectionalClass::WEAK_SEPARATORS)
  869. character_classes[i] = paragraph_class;
  870. }
  871. // resolving neutral types
  872. auto left_side = BidirectionalClass::NEUTRAL;
  873. auto sequence_length = 0;
  874. for (size_t i = 0; i < character_classes.size(); i++) {
  875. auto character_class = character_classes[i];
  876. if (left_side == BidirectionalClass::NEUTRAL) {
  877. if (character_class != BidirectionalClass::NEUTRAL)
  878. left_side = character_class;
  879. else
  880. character_classes[i] = paragraph_class;
  881. continue;
  882. }
  883. if (character_class != BidirectionalClass::NEUTRAL) {
  884. BidirectionalClass sequence_class;
  885. if (bidi_class_to_direction(left_side) == bidi_class_to_direction(character_class)) {
  886. sequence_class = left_side == BidirectionalClass::STRONG_RTL ? BidirectionalClass::STRONG_RTL : BidirectionalClass::STRONG_LTR;
  887. } else {
  888. sequence_class = paragraph_class;
  889. }
  890. for (auto j = 0; j < sequence_length; j++) {
  891. character_classes[i - j - 1] = sequence_class;
  892. }
  893. sequence_length = 0;
  894. left_side = character_class;
  895. } else {
  896. sequence_length++;
  897. }
  898. }
  899. for (auto i = 0; i < sequence_length; i++)
  900. character_classes[character_classes.size() - i - 1] = paragraph_class;
  901. // resolving implicit levels
  902. for (size_t i = 0; i < character_classes.size(); i++) {
  903. auto character_class = character_classes[i];
  904. if ((embedding_levels[i] % 2) == 0) {
  905. if (character_class == BidirectionalClass::STRONG_RTL)
  906. embedding_levels[i] += 1;
  907. else if (character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  908. embedding_levels[i] += 2;
  909. } else {
  910. if (character_class == BidirectionalClass::STRONG_LTR || character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  911. embedding_levels[i] += 1;
  912. }
  913. }
  914. // splitting into runs
  915. auto run_code_points_start = text.begin();
  916. auto next_code_points_slice = [&](auto length) {
  917. Vector<u32> run_code_points;
  918. run_code_points.ensure_capacity(length);
  919. for (size_t j = 0; j < length; ++j, ++run_code_points_start)
  920. run_code_points.unchecked_append(*run_code_points_start);
  921. return run_code_points;
  922. };
  923. Vector<DirectionalRun> runs;
  924. size_t start = 0;
  925. u8 level = embedding_levels[0];
  926. for (size_t i = 1; i < embedding_levels.size(); ++i) {
  927. if (embedding_levels[i] == level)
  928. continue;
  929. auto code_points_slice = next_code_points_slice(i - start);
  930. runs.append({ move(code_points_slice), level });
  931. start = i;
  932. level = embedding_levels[i];
  933. }
  934. auto code_points_slice = next_code_points_slice(embedding_levels.size() - start);
  935. runs.append({ move(code_points_slice), level });
  936. // reordering resolved levels
  937. // FIXME: missing special cases for trailing whitespace characters
  938. u8 minimum_level = 128;
  939. u8 maximum_level = 0;
  940. for (auto& run : runs) {
  941. minimum_level = min(minimum_level, run.embedding_level());
  942. maximum_level = max(minimum_level, run.embedding_level());
  943. }
  944. if ((minimum_level % 2) == 0)
  945. minimum_level++;
  946. auto runs_count = runs.size() - 1;
  947. while (maximum_level <= minimum_level) {
  948. size_t run_index = 0;
  949. while (run_index < runs_count) {
  950. while (run_index < runs_count && runs[run_index].embedding_level() < maximum_level)
  951. run_index++;
  952. auto reverse_start = run_index;
  953. while (run_index <= runs_count && runs[run_index].embedding_level() >= maximum_level)
  954. run_index++;
  955. auto reverse_end = run_index - 1;
  956. while (reverse_start < reverse_end) {
  957. swap(runs[reverse_start], runs[reverse_end]);
  958. reverse_start++;
  959. reverse_end--;
  960. }
  961. }
  962. maximum_level--;
  963. }
  964. // mirroring RTL mirror characters
  965. for (auto& run : runs) {
  966. if (run.direction() == TextDirection::LTR)
  967. continue;
  968. for (auto& code_point : run.code_points()) {
  969. code_point = get_mirror_char(code_point);
  970. }
  971. }
  972. return runs;
  973. }
  974. bool Painter::text_contains_bidirectional_text(Utf8View const& text, TextDirection initial_direction)
  975. {
  976. for (u32 code_point : text) {
  977. auto char_class = get_char_bidi_class(code_point);
  978. if (char_class == BidirectionalClass::NEUTRAL)
  979. continue;
  980. if (bidi_class_to_direction(char_class) != initial_direction)
  981. return true;
  982. }
  983. return false;
  984. }
  985. template<typename DrawGlyphFunction>
  986. void Painter::do_draw_text(FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping, DrawGlyphFunction draw_glyph)
  987. {
  988. if (draw_text_get_length(text) == 0)
  989. return;
  990. TextLayout layout(font, text, rect);
  991. auto line_height = font.preferred_line_height();
  992. auto lines = layout.lines(elision, wrapping);
  993. auto bounding_rect = layout.bounding_rect(wrapping);
  994. bounding_rect.align_within(rect, alignment);
  995. for (size_t i = 0; i < lines.size(); ++i) {
  996. auto line = Utf8View { lines[i] };
  997. FloatRect line_rect { bounding_rect.x(), bounding_rect.y() + i * line_height, bounding_rect.width(), line_height };
  998. TextDirection line_direction = get_text_direction(line);
  999. if (text_contains_bidirectional_text(line, line_direction)) { // Slow Path: The line contains mixed BiDi classes
  1000. auto directional_runs = split_text_into_directional_runs(line, line_direction);
  1001. auto current_dx = line_direction == TextDirection::LTR ? 0 : line_rect.width();
  1002. for (auto& directional_run : directional_runs) {
  1003. // NOTE: DirectionalRun returns Utf32View which isn't
  1004. // compatible with draw_text_line.
  1005. StringBuilder builder;
  1006. builder.append(directional_run.text());
  1007. auto line_text = Utf8View { builder.string_view() };
  1008. auto run_width = font.width(line_text);
  1009. if (line_direction == TextDirection::RTL)
  1010. current_dx -= run_width;
  1011. auto run_rect = line_rect.translated(current_dx, 0);
  1012. run_rect.set_width(run_width);
  1013. draw_text_line(run_rect, line_text, font, alignment, directional_run.direction(), draw_glyph);
  1014. if (line_direction == TextDirection::LTR)
  1015. current_dx += run_width;
  1016. }
  1017. } else {
  1018. draw_text_line(line_rect, line, font, alignment, line_direction, draw_glyph);
  1019. }
  1020. }
  1021. }
  1022. void Painter::draw_text(FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1023. {
  1024. Utf8View text { raw_text };
  1025. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1026. draw_glyph_or_emoji(r.location(), it, font, color);
  1027. });
  1028. }
  1029. void Painter::draw_text(IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1030. {
  1031. draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1032. }
  1033. void Painter::set_pixel(IntPoint p, Color color, bool blend)
  1034. {
  1035. auto point = p;
  1036. point.translate_by(state().translation);
  1037. // Use the scale only to avoid clipping pixels set in drawing functions that handle
  1038. // scaling and call set_pixel() -- do not scale the pixel.
  1039. if (!clip_rect().contains(point))
  1040. return;
  1041. set_physical_pixel(point, color, blend);
  1042. }
  1043. void Painter::set_physical_pixel(IntPoint physical_point, Color color, bool blend)
  1044. {
  1045. // This function should only be called after translation, clipping, etc has been handled elsewhere
  1046. // if not use set_pixel().
  1047. auto& dst = target().scanline(physical_point.y())[physical_point.x()];
  1048. if (!blend || color.alpha() == 255)
  1049. dst = color.value();
  1050. else if (color.alpha())
  1051. dst = color_for_format(target().format(), dst).blend(color).value();
  1052. }
  1053. Optional<Color> Painter::get_pixel(IntPoint p)
  1054. {
  1055. auto point = p;
  1056. point.translate_by(state().translation);
  1057. if (!clip_rect().contains(point))
  1058. return {};
  1059. return target().get_pixel(point);
  1060. }
  1061. ErrorOr<NonnullRefPtr<Bitmap>> Painter::get_region_bitmap(IntRect const& region, BitmapFormat format, Optional<IntRect&> actual_region)
  1062. {
  1063. auto bitmap_region = region.translated(state().translation).intersected(target().rect());
  1064. if (actual_region.has_value())
  1065. actual_region.value() = bitmap_region.translated(-state().translation);
  1066. return target().cropped(bitmap_region, format);
  1067. }
  1068. ALWAYS_INLINE void Painter::set_physical_pixel(u32& pixel, Color color)
  1069. {
  1070. // This always sets a single physical pixel, independent of scale().
  1071. // This should only be called by routines that already handle scale.
  1072. pixel = color.value();
  1073. }
  1074. ALWAYS_INLINE void Painter::fill_physical_scanline(int y, int x, int width, Color color)
  1075. {
  1076. // This always draws a single physical scanline, independent of scale().
  1077. // This should only be called by routines that already handle scale.
  1078. fast_u32_fill(target().scanline(y) + x, color.value(), width);
  1079. }
  1080. void Painter::draw_physical_pixel(IntPoint physical_position, Color color, int thickness)
  1081. {
  1082. // This always draws a single physical pixel, independent of scale().
  1083. // This should only be called by routines that already handle scale
  1084. // (including scaling thickness).
  1085. if (thickness <= 0)
  1086. return;
  1087. if (thickness == 1) { // Implies scale() == 1.
  1088. auto& pixel = target().scanline(physical_position.y())[physical_position.x()];
  1089. return set_physical_pixel(pixel, color_for_format(target().format(), pixel).blend(color));
  1090. }
  1091. IntRect rect { physical_position, { thickness, thickness } };
  1092. rect.intersect(clip_rect());
  1093. fill_physical_rect(rect, color);
  1094. }
  1095. void Painter::draw_line(IntPoint a_p1, IntPoint a_p2, Color color, int thickness, LineStyle style, Color alternate_color)
  1096. {
  1097. if (clip_rect().is_empty())
  1098. return;
  1099. if (thickness <= 0)
  1100. return;
  1101. if (color.alpha() == 0)
  1102. return;
  1103. auto clip_rect = this->clip_rect();
  1104. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1105. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1106. auto point1 = to_physical(p1);
  1107. auto point2 = to_physical(p2);
  1108. auto alternate_color_is_transparent = alternate_color == Color::Transparent;
  1109. // Special case: vertical line.
  1110. if (point1.x() == point2.x()) {
  1111. int const x = point1.x();
  1112. if (x < clip_rect.left() || x >= clip_rect.right())
  1113. return;
  1114. if (point1.y() > point2.y())
  1115. swap(point1, point2);
  1116. if (point1.y() >= clip_rect.bottom())
  1117. return;
  1118. if (point2.y() < clip_rect.top())
  1119. return;
  1120. int min_y = max(point1.y(), clip_rect.top());
  1121. int max_y = min(point2.y(), clip_rect.bottom() - 1);
  1122. if (style == LineStyle::Dotted) {
  1123. for (int y = min_y; y <= max_y; y += thickness * 2)
  1124. draw_physical_pixel({ x, y }, color, thickness);
  1125. } else if (style == LineStyle::Dashed) {
  1126. for (int y = min_y; y <= max_y; y += thickness * 6) {
  1127. draw_physical_pixel({ x, y }, color, thickness);
  1128. draw_physical_pixel({ x, min(y + thickness, max_y) }, color, thickness);
  1129. draw_physical_pixel({ x, min(y + thickness * 2, max_y) }, color, thickness);
  1130. if (!alternate_color_is_transparent) {
  1131. draw_physical_pixel({ x, min(y + thickness * 3, max_y) }, alternate_color, thickness);
  1132. draw_physical_pixel({ x, min(y + thickness * 4, max_y) }, alternate_color, thickness);
  1133. draw_physical_pixel({ x, min(y + thickness * 5, max_y) }, alternate_color, thickness);
  1134. }
  1135. }
  1136. } else {
  1137. for (int y = min_y; y <= max_y; y += thickness)
  1138. draw_physical_pixel({ x, y }, color, thickness);
  1139. draw_physical_pixel({ x, max_y }, color, thickness);
  1140. }
  1141. return;
  1142. }
  1143. // Special case: horizontal line.
  1144. if (point1.y() == point2.y()) {
  1145. int const y = point1.y();
  1146. if (y < clip_rect.top() || y >= clip_rect.bottom())
  1147. return;
  1148. if (point1.x() > point2.x())
  1149. swap(point1, point2);
  1150. if (point1.x() >= clip_rect.right())
  1151. return;
  1152. if (point2.x() < clip_rect.left())
  1153. return;
  1154. int min_x = max(point1.x(), clip_rect.left());
  1155. int max_x = min(point2.x(), clip_rect.right() - 1);
  1156. if (style == LineStyle::Dotted) {
  1157. for (int x = min_x; x <= max_x; x += thickness * 2)
  1158. draw_physical_pixel({ x, y }, color, thickness);
  1159. } else if (style == LineStyle::Dashed) {
  1160. for (int x = min_x; x <= max_x; x += thickness * 6) {
  1161. draw_physical_pixel({ x, y }, color, thickness);
  1162. draw_physical_pixel({ min(x + thickness, max_x), y }, color, thickness);
  1163. draw_physical_pixel({ min(x + thickness * 2, max_x), y }, color, thickness);
  1164. if (!alternate_color_is_transparent) {
  1165. draw_physical_pixel({ min(x + thickness * 3, max_x), y }, alternate_color, thickness);
  1166. draw_physical_pixel({ min(x + thickness * 4, max_x), y }, alternate_color, thickness);
  1167. draw_physical_pixel({ min(x + thickness * 5, max_x), y }, alternate_color, thickness);
  1168. }
  1169. }
  1170. } else {
  1171. for (int x = min_x; x <= max_x; x += thickness)
  1172. draw_physical_pixel({ x, y }, color, thickness);
  1173. draw_physical_pixel({ max_x, y }, color, thickness);
  1174. }
  1175. return;
  1176. }
  1177. int const adx = abs(point2.x() - point1.x());
  1178. int const ady = abs(point2.y() - point1.y());
  1179. if (adx > ady) {
  1180. if (point1.x() > point2.x())
  1181. swap(point1, point2);
  1182. } else {
  1183. if (point1.y() > point2.y())
  1184. swap(point1, point2);
  1185. }
  1186. int const dx = point2.x() - point1.x();
  1187. int const dy = point2.y() - point1.y();
  1188. int error = 0;
  1189. size_t number_of_pixels_drawn = 0;
  1190. auto draw_pixel_in_line = [&](int x, int y) {
  1191. bool should_draw_line = true;
  1192. if (style == LineStyle::Dotted && number_of_pixels_drawn % 2 == 1)
  1193. should_draw_line = false;
  1194. else if (style == LineStyle::Dashed && number_of_pixels_drawn % 6 >= 3)
  1195. should_draw_line = false;
  1196. if (should_draw_line)
  1197. draw_physical_pixel({ x, y }, color, thickness);
  1198. else if (!alternate_color_is_transparent)
  1199. draw_physical_pixel({ x, y }, alternate_color, thickness);
  1200. number_of_pixels_drawn++;
  1201. };
  1202. if (dx > dy) {
  1203. int const y_step = dy == 0 ? 0 : (dy > 0 ? 1 : -1);
  1204. int const delta_error = 2 * abs(dy);
  1205. int y = point1.y();
  1206. for (int x = point1.x(); x <= point2.x(); ++x) {
  1207. if (clip_rect.contains(x, y))
  1208. draw_pixel_in_line(x, y);
  1209. error += delta_error;
  1210. if (error >= dx) {
  1211. y += y_step;
  1212. error -= 2 * dx;
  1213. }
  1214. }
  1215. } else {
  1216. int const x_step = dx == 0 ? 0 : (dx > 0 ? 1 : -1);
  1217. int const delta_error = 2 * abs(dx);
  1218. int x = point1.x();
  1219. for (int y = point1.y(); y <= point2.y(); ++y) {
  1220. if (clip_rect.contains(x, y))
  1221. draw_pixel_in_line(x, y);
  1222. error += delta_error;
  1223. if (error >= dy) {
  1224. x += x_step;
  1225. error -= 2 * dy;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. void Painter::draw_triangle_wave(IntPoint a_p1, IntPoint a_p2, Color color, int amplitude, int thickness)
  1231. {
  1232. // FIXME: Support more than horizontal waves
  1233. VERIFY(a_p1.y() == a_p2.y());
  1234. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1235. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1236. auto point1 = to_physical(p1);
  1237. auto point2 = to_physical(p2);
  1238. auto y = point1.y();
  1239. for (int x = 0; x <= point2.x() - point1.x(); ++x) {
  1240. auto y_offset = abs(x % (2 * amplitude) - amplitude) - amplitude;
  1241. draw_physical_pixel({ point1.x() + x, y + y_offset }, color, thickness);
  1242. }
  1243. }
  1244. static bool can_approximate_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control)
  1245. {
  1246. // TODO: Somehow calculate the required number of splits based on the curve (and its size).
  1247. constexpr float tolerance = 0.5f;
  1248. auto p1x = 3 * control.x() - 2 * p1.x() - p2.x();
  1249. auto p1y = 3 * control.y() - 2 * p1.y() - p2.y();
  1250. auto p2x = 3 * control.x() - 2 * p2.x() - p1.x();
  1251. auto p2y = 3 * control.y() - 2 * p2.y() - p1.y();
  1252. p1x = p1x * p1x;
  1253. p1y = p1y * p1y;
  1254. p2x = p2x * p2x;
  1255. p2y = p2y * p2y;
  1256. auto error = max(p1x, p2x) + max(p1y, p2y);
  1257. VERIFY(isfinite(error));
  1258. return error <= tolerance;
  1259. }
  1260. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1261. {
  1262. struct SegmentDescriptor {
  1263. FloatPoint control_point;
  1264. FloatPoint p1;
  1265. FloatPoint p2;
  1266. };
  1267. static constexpr auto split_quadratic_bezier_curve = [](FloatPoint original_control, FloatPoint p1, FloatPoint p2, auto& segments) {
  1268. auto po1_midpoint = original_control + p1;
  1269. po1_midpoint /= 2;
  1270. auto po2_midpoint = original_control + p2;
  1271. po2_midpoint /= 2;
  1272. auto new_segment = po1_midpoint + po2_midpoint;
  1273. new_segment /= 2;
  1274. segments.append({ po2_midpoint, new_segment, p2 });
  1275. segments.append({ po1_midpoint, p1, new_segment });
  1276. };
  1277. Vector<SegmentDescriptor> segments;
  1278. segments.append({ control_point, p1, p2 });
  1279. while (!segments.is_empty()) {
  1280. auto segment = segments.take_last();
  1281. if (can_approximate_bezier_curve(segment.p1, segment.p2, segment.control_point))
  1282. callback(segment.p1, segment.p2);
  1283. else
  1284. split_quadratic_bezier_curve(segment.control_point, segment.p1, segment.p2, segments);
  1285. }
  1286. }
  1287. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1288. {
  1289. for_each_line_segment_on_bezier_curve(control_point, p1, p2, callback);
  1290. }
  1291. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint control_point_0, FloatPoint control_point_1, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1292. {
  1293. for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback);
  1294. }
  1295. static bool can_approximate_cubic_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control_0, FloatPoint control_1)
  1296. {
  1297. // TODO: Somehow calculate the required number of splits based on the curve (and its size).
  1298. constexpr float tolerance = 0.5f;
  1299. auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x();
  1300. auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y();
  1301. auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x();
  1302. auto by = 3 * control_1.y() - p1.y() - 2 * p2.y();
  1303. ax *= ax;
  1304. ay *= ay;
  1305. bx *= bx;
  1306. by *= by;
  1307. auto error = max(ax, bx) + max(ay, by);
  1308. VERIFY(isfinite(error));
  1309. return error <= tolerance;
  1310. }
  1311. // static
  1312. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint control_point_0, FloatPoint control_point_1, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1313. {
  1314. struct ControlPair {
  1315. FloatPoint control_point_0;
  1316. FloatPoint control_point_1;
  1317. };
  1318. struct SegmentDescriptor {
  1319. ControlPair control_points;
  1320. FloatPoint p1;
  1321. FloatPoint p2;
  1322. };
  1323. static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint p1, FloatPoint p2, auto& segments) {
  1324. Array level_1_midpoints {
  1325. (p1 + original_controls.control_point_0) / 2,
  1326. (original_controls.control_point_0 + original_controls.control_point_1) / 2,
  1327. (original_controls.control_point_1 + p2) / 2,
  1328. };
  1329. Array level_2_midpoints {
  1330. (level_1_midpoints[0] + level_1_midpoints[1]) / 2,
  1331. (level_1_midpoints[1] + level_1_midpoints[2]) / 2,
  1332. };
  1333. auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2;
  1334. segments.append({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 });
  1335. segments.append({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint });
  1336. };
  1337. Vector<SegmentDescriptor> segments;
  1338. segments.append({ { control_point_0, control_point_1 }, p1, p2 });
  1339. while (!segments.is_empty()) {
  1340. auto segment = segments.take_last();
  1341. if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1))
  1342. callback(segment.p1, segment.p2);
  1343. else
  1344. split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments);
  1345. }
  1346. }
  1347. void Painter::add_clip_rect(IntRect const& rect)
  1348. {
  1349. state().clip_rect.intersect(rect.translated(translation()));
  1350. state().clip_rect.intersect(target().rect()); // FIXME: This shouldn't be necessary?
  1351. }
  1352. void Painter::clear_clip_rect()
  1353. {
  1354. state().clip_rect = m_clip_origin;
  1355. }
  1356. PainterStateSaver::PainterStateSaver(Painter& painter)
  1357. : m_painter(painter)
  1358. {
  1359. m_painter.save();
  1360. }
  1361. PainterStateSaver::~PainterStateSaver()
  1362. {
  1363. m_painter.restore();
  1364. }
  1365. void Painter::stroke_path(Path const& path, Color color, int thickness)
  1366. {
  1367. if (thickness <= 0)
  1368. return;
  1369. fill_path(path.stroke_to_fill(thickness), color);
  1370. }
  1371. void Painter::draw_scaled_bitmap_with_transform(IntRect const& dst_rect, Bitmap const& bitmap, FloatRect const& src_rect, AffineTransform const& transform, float opacity, ScalingMode scaling_mode)
  1372. {
  1373. if (transform.is_identity_or_translation_or_scale()) {
  1374. draw_scaled_bitmap(transform.map(dst_rect.to_type<float>()).to_rounded<int>(), bitmap, src_rect, opacity, scaling_mode);
  1375. } else {
  1376. // The painter has an affine transform, we have to draw through it!
  1377. // FIXME: This is kinda inefficient.
  1378. // What we currently do, roughly:
  1379. // - Map the destination rect through the context's transform.
  1380. // - Compute the bounding rect of the destination quad.
  1381. // - For each point in the clipped bounding rect, reverse-map it to a point in the source image.
  1382. // - Sample the source image at the computed point.
  1383. // - Set or blend (depending on alpha values) one pixel in the canvas.
  1384. // - Loop.
  1385. // FIXME: Painter should have an affine transform as part of its state and handle all of this instead.
  1386. if (opacity == 0.0f)
  1387. return;
  1388. auto inverse_transform = transform.inverse();
  1389. if (!inverse_transform.has_value())
  1390. return;
  1391. auto destination_quad = transform.map_to_quad(dst_rect.to_type<float>());
  1392. auto destination_bounding_rect = destination_quad.bounding_rect().to_rounded<int>();
  1393. auto source_rect = enclosing_int_rect(src_rect).intersected(bitmap.rect());
  1394. Gfx::AffineTransform source_transform;
  1395. source_transform.translate(src_rect.x(), src_rect.y());
  1396. source_transform.scale(src_rect.width() / dst_rect.width(), src_rect.height() / dst_rect.height());
  1397. source_transform.translate(-dst_rect.x(), -dst_rect.y());
  1398. auto translated_dest_rect = destination_bounding_rect.translated(translation());
  1399. auto clipped_bounding_rect = translated_dest_rect.intersected(clip_rect());
  1400. if (clipped_bounding_rect.is_empty())
  1401. return;
  1402. auto sample_transform = source_transform.multiply(*inverse_transform);
  1403. auto start_offset = destination_bounding_rect.location() + (clipped_bounding_rect.location() - translated_dest_rect.location());
  1404. for (int y = 0; y < clipped_bounding_rect.height(); ++y) {
  1405. for (int x = 0; x < clipped_bounding_rect.width(); ++x) {
  1406. auto point = Gfx::IntPoint { x, y };
  1407. auto sample_point = point + start_offset;
  1408. // AffineTransform::map(IntPoint) rounds internally, which is wrong here. So explicitly call the FloatPoint version, and then truncate the result.
  1409. auto source_point = Gfx::IntPoint { sample_transform.map(Gfx::FloatPoint { sample_point }) };
  1410. if (!source_rect.contains(source_point))
  1411. continue;
  1412. auto source_color = bitmap.get_pixel(source_point);
  1413. if (source_color.alpha() == 0)
  1414. continue;
  1415. if (opacity != 1.0f)
  1416. source_color = source_color.with_opacity(opacity);
  1417. set_physical_pixel(point + clipped_bounding_rect.location(), source_color, true);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. }