Painter.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  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 "Font/FontDatabase.h"
  17. #include "Gamma.h"
  18. #include <AK/Assertions.h>
  19. #include <AK/Debug.h>
  20. #include <AK/Function.h>
  21. #include <AK/Math.h>
  22. #include <AK/Memory.h>
  23. #include <AK/Queue.h>
  24. #include <AK/QuickSort.h>
  25. #include <AK/StdLibExtras.h>
  26. #include <AK/StringBuilder.h>
  27. #include <AK/Utf32View.h>
  28. #include <AK/Utf8View.h>
  29. #include <LibGfx/CharacterBitmap.h>
  30. #include <LibGfx/FillPathImplementation.h>
  31. #include <LibGfx/Palette.h>
  32. #include <LibGfx/Path.h>
  33. #include <LibGfx/Quad.h>
  34. #include <LibGfx/TextDirection.h>
  35. #include <LibGfx/TextLayout.h>
  36. #include <stdio.h>
  37. #if defined(AK_COMPILER_GCC)
  38. # pragma GCC optimize("O3")
  39. #endif
  40. namespace Gfx {
  41. static bool should_paint_as_space(u32 code_point)
  42. {
  43. return is_ascii_space(code_point) || code_point == 0xa0;
  44. }
  45. template<BitmapFormat format = BitmapFormat::Invalid>
  46. ALWAYS_INLINE Color get_pixel(Gfx::Bitmap const& bitmap, int x, int y)
  47. {
  48. if constexpr (format == BitmapFormat::Indexed8)
  49. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  50. if constexpr (format == BitmapFormat::Indexed4)
  51. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  52. if constexpr (format == BitmapFormat::Indexed2)
  53. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  54. if constexpr (format == BitmapFormat::Indexed1)
  55. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  56. if constexpr (format == BitmapFormat::BGRx8888)
  57. return Color::from_rgb(bitmap.scanline(y)[x]);
  58. if constexpr (format == BitmapFormat::BGRA8888)
  59. return Color::from_argb(bitmap.scanline(y)[x]);
  60. return bitmap.get_pixel(x, y);
  61. }
  62. Painter::Painter(Gfx::Bitmap& bitmap)
  63. : m_target(bitmap)
  64. {
  65. int scale = bitmap.scale();
  66. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRx8888 || bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  67. VERIFY(bitmap.physical_width() % scale == 0);
  68. VERIFY(bitmap.physical_height() % scale == 0);
  69. m_state_stack.append(State());
  70. state().font = nullptr;
  71. state().clip_rect = { { 0, 0 }, bitmap.size() };
  72. state().scale = scale;
  73. m_clip_origin = state().clip_rect;
  74. }
  75. void Painter::fill_rect_with_draw_op(IntRect const& a_rect, Color color)
  76. {
  77. VERIFY(scale() == 1); // FIXME: Add scaling support.
  78. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  79. if (rect.is_empty())
  80. return;
  81. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  82. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  83. for (int i = rect.height() - 1; i >= 0; --i) {
  84. for (int j = 0; j < rect.width(); ++j)
  85. set_physical_pixel_with_draw_op(dst[j], color);
  86. dst += dst_skip;
  87. }
  88. }
  89. void Painter::clear_rect(IntRect const& a_rect, Color color)
  90. {
  91. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  92. if (rect.is_empty())
  93. return;
  94. VERIFY(m_target->rect().contains(rect));
  95. rect *= scale();
  96. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  97. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  98. for (int i = rect.height() - 1; i >= 0; --i) {
  99. fast_u32_fill(dst, color.value(), rect.width());
  100. dst += dst_skip;
  101. }
  102. }
  103. void Painter::fill_physical_rect(IntRect const& physical_rect, Color color)
  104. {
  105. // Callers must do clipping.
  106. ARGB32* dst = m_target->scanline(physical_rect.top()) + physical_rect.left();
  107. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  108. for (int i = physical_rect.height() - 1; i >= 0; --i) {
  109. for (int j = 0; j < physical_rect.width(); ++j)
  110. dst[j] = Color::from_argb(dst[j]).blend(color).value();
  111. dst += dst_skip;
  112. }
  113. }
  114. void Painter::fill_rect(IntRect const& a_rect, Color color)
  115. {
  116. if (color.alpha() == 0)
  117. return;
  118. if (draw_op() != DrawOp::Copy) {
  119. fill_rect_with_draw_op(a_rect, color);
  120. return;
  121. }
  122. if (color.alpha() == 0xff) {
  123. clear_rect(a_rect, color);
  124. return;
  125. }
  126. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  127. if (rect.is_empty())
  128. return;
  129. VERIFY(m_target->rect().contains(rect));
  130. fill_physical_rect(rect * scale(), color);
  131. }
  132. void Painter::fill_rect_with_dither_pattern(IntRect const& a_rect, Color color_a, Color color_b)
  133. {
  134. VERIFY(scale() == 1); // FIXME: Add scaling support.
  135. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  136. if (rect.is_empty())
  137. return;
  138. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  139. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  140. for (int i = 0; i < rect.height(); ++i) {
  141. for (int j = 0; j < rect.width(); ++j) {
  142. bool checkboard_use_a = ((rect.left() + i) & 1) ^ ((rect.top() + j) & 1);
  143. if (checkboard_use_a && !color_a.alpha())
  144. continue;
  145. if (!checkboard_use_a && !color_b.alpha())
  146. continue;
  147. dst[j] = checkboard_use_a ? color_a.value() : color_b.value();
  148. }
  149. dst += dst_skip;
  150. }
  151. }
  152. void Painter::fill_rect_with_checkerboard(IntRect const& a_rect, IntSize cell_size, Color color_dark, Color color_light)
  153. {
  154. VERIFY(scale() == 1); // FIXME: Add scaling support.
  155. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  156. if (rect.is_empty())
  157. return;
  158. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  159. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  160. int first_cell_column = rect.x() / cell_size.width();
  161. int prologue_length = min(rect.width(), cell_size.width() - (rect.x() % cell_size.width()));
  162. int number_of_aligned_strips = (rect.width() - prologue_length) / cell_size.width();
  163. for (int i = 0; i < rect.height(); ++i) {
  164. int y = rect.y() + i;
  165. int cell_row = y / cell_size.height();
  166. bool odd_row = cell_row & 1;
  167. // Prologue: Paint the unaligned part up to the first intersection.
  168. int j = 0;
  169. int cell_column = first_cell_column;
  170. {
  171. bool odd_cell = cell_column & 1;
  172. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  173. fast_u32_fill(&dst[j], color, prologue_length);
  174. j += prologue_length;
  175. }
  176. // Aligned run: Paint the maximum number of aligned cell strips.
  177. for (int strip = 0; strip < number_of_aligned_strips; ++strip) {
  178. ++cell_column;
  179. bool odd_cell = cell_column & 1;
  180. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  181. fast_u32_fill(&dst[j], color, cell_size.width());
  182. j += cell_size.width();
  183. }
  184. // Epilogue: Paint the unaligned part until the end of the rect.
  185. if (j != rect.width()) {
  186. ++cell_column;
  187. bool odd_cell = cell_column & 1;
  188. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  189. int epilogue_length = rect.width() - j;
  190. fast_u32_fill(&dst[j], color, epilogue_length);
  191. j += epilogue_length;
  192. }
  193. dst += dst_skip;
  194. }
  195. }
  196. void Painter::fill_rect_with_gradient(Orientation orientation, IntRect const& a_rect, Color gradient_start, Color gradient_end)
  197. {
  198. if (gradient_start == gradient_end) {
  199. fill_rect(a_rect, gradient_start);
  200. return;
  201. }
  202. return fill_rect_with_linear_gradient(a_rect, Array { ColorStop { gradient_start, 0 }, ColorStop { gradient_end, 1 } }, orientation == Orientation::Horizontal ? 90.0f : 0.0f);
  203. }
  204. void Painter::fill_rect_with_gradient(IntRect const& a_rect, Color gradient_start, Color gradient_end)
  205. {
  206. return fill_rect_with_gradient(Orientation::Horizontal, a_rect, gradient_start, gradient_end);
  207. }
  208. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  209. {
  210. return fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  211. }
  212. 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)
  213. {
  214. // Fasttrack for rects without any border radii
  215. if (!top_left_radius && !top_right_radius && !bottom_right_radius && !bottom_left_radius)
  216. return fill_rect(a_rect, color);
  217. // Fully transparent, dont care.
  218. if (color.alpha() == 0)
  219. return;
  220. // FIXME: Allow for elliptically rounded corners
  221. IntRect top_left_corner = {
  222. a_rect.x(),
  223. a_rect.y(),
  224. top_left_radius,
  225. top_left_radius
  226. };
  227. IntRect top_right_corner = {
  228. a_rect.x() + a_rect.width() - top_right_radius,
  229. a_rect.y(),
  230. top_right_radius,
  231. top_right_radius
  232. };
  233. IntRect bottom_right_corner = {
  234. a_rect.x() + a_rect.width() - bottom_right_radius,
  235. a_rect.y() + a_rect.height() - bottom_right_radius,
  236. bottom_right_radius,
  237. bottom_right_radius
  238. };
  239. IntRect bottom_left_corner = {
  240. a_rect.x(),
  241. a_rect.y() + a_rect.height() - bottom_left_radius,
  242. bottom_left_radius,
  243. bottom_left_radius
  244. };
  245. IntRect top_rect = {
  246. a_rect.x() + top_left_radius,
  247. a_rect.y(),
  248. a_rect.width() - top_left_radius - top_right_radius, top_left_radius
  249. };
  250. IntRect right_rect = {
  251. a_rect.x() + a_rect.width() - top_right_radius,
  252. a_rect.y() + top_right_radius,
  253. top_right_radius,
  254. a_rect.height() - top_right_radius - bottom_right_radius
  255. };
  256. IntRect bottom_rect = {
  257. a_rect.x() + bottom_left_radius,
  258. a_rect.y() + a_rect.height() - bottom_right_radius,
  259. a_rect.width() - bottom_left_radius - bottom_right_radius,
  260. bottom_right_radius
  261. };
  262. IntRect left_rect = {
  263. a_rect.x(),
  264. a_rect.y() + top_left_radius,
  265. bottom_left_radius,
  266. a_rect.height() - top_left_radius - bottom_left_radius
  267. };
  268. IntRect inner = {
  269. left_rect.x() + left_rect.width(),
  270. left_rect.y(),
  271. a_rect.width() - left_rect.width() - right_rect.width(),
  272. a_rect.height() - top_rect.height() - bottom_rect.height()
  273. };
  274. fill_rect(top_rect, color);
  275. fill_rect(right_rect, color);
  276. fill_rect(bottom_rect, color);
  277. fill_rect(left_rect, color);
  278. fill_rect(inner, color);
  279. if (top_left_radius)
  280. fill_rounded_corner(top_left_corner, top_left_radius, color, CornerOrientation::TopLeft);
  281. if (top_right_radius)
  282. fill_rounded_corner(top_right_corner, top_right_radius, color, CornerOrientation::TopRight);
  283. if (bottom_left_radius)
  284. fill_rounded_corner(bottom_left_corner, bottom_left_radius, color, CornerOrientation::BottomLeft);
  285. if (bottom_right_radius)
  286. fill_rounded_corner(bottom_right_corner, bottom_right_radius, color, CornerOrientation::BottomRight);
  287. }
  288. void Painter::fill_rounded_corner(IntRect const& a_rect, int radius, Color color, CornerOrientation orientation)
  289. {
  290. // Care about clipping
  291. auto translated_a_rect = a_rect.translated(translation());
  292. auto rect = translated_a_rect.intersected(clip_rect());
  293. if (rect.is_empty())
  294. return;
  295. VERIFY(m_target->rect().contains(rect));
  296. // We got cut on the top!
  297. // FIXME: Also account for clipping on the x-axis
  298. int clip_offset = 0;
  299. if (translated_a_rect.y() < rect.y())
  300. clip_offset = rect.y() - translated_a_rect.y();
  301. radius *= scale();
  302. rect *= scale();
  303. clip_offset *= scale();
  304. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  305. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  306. IntPoint circle_center;
  307. switch (orientation) {
  308. case CornerOrientation::TopLeft:
  309. circle_center = { radius, radius + 1 };
  310. break;
  311. case CornerOrientation::TopRight:
  312. circle_center = { -1, radius + 1 };
  313. break;
  314. case CornerOrientation::BottomRight:
  315. circle_center = { -1, 0 };
  316. break;
  317. case CornerOrientation::BottomLeft:
  318. circle_center = { radius, 0 };
  319. break;
  320. default:
  321. VERIFY_NOT_REACHED();
  322. }
  323. int radius2 = radius * radius;
  324. auto is_in_circle = [&](int x, int y) {
  325. int distance2 = (circle_center.x() - x) * (circle_center.x() - x) + (circle_center.y() - y) * (circle_center.y() - y);
  326. // To reflect the grid and be compatible with the draw_circle_arc_intersecting algorithm
  327. // add 1/2 to the radius
  328. return distance2 <= (radius2 + radius + 0.25);
  329. };
  330. for (int i = rect.height() - 1; i >= 0; --i) {
  331. for (int j = 0; j < rect.width(); ++j)
  332. if (is_in_circle(j, rect.height() - i + clip_offset))
  333. dst[j] = Color::from_argb(dst[j]).blend(color).value();
  334. dst += dst_skip;
  335. }
  336. }
  337. void Painter::draw_circle_arc_intersecting(IntRect const& a_rect, IntPoint center, int radius, Color color, int thickness)
  338. {
  339. if (thickness <= 0 || radius <= 0)
  340. return;
  341. // Care about clipping
  342. auto translated_a_rect = a_rect.translated(translation());
  343. auto rect = translated_a_rect.intersected(clip_rect());
  344. if (rect.is_empty())
  345. return;
  346. VERIFY(m_target->rect().contains(rect));
  347. // We got cut on the top!
  348. // FIXME: Also account for clipping on the x-axis
  349. int clip_offset = 0;
  350. if (translated_a_rect.y() < rect.y())
  351. clip_offset = rect.y() - translated_a_rect.y();
  352. if (thickness > radius)
  353. thickness = radius;
  354. int radius2 = radius * radius;
  355. auto is_on_arc = [&](int x, int y) {
  356. int distance2 = (center.x() - x) * (center.x() - x) + (center.y() - y) * (center.y() - y);
  357. // Is within a circle of radius 1/2 around (x,y), so basically within the current pixel.
  358. // Technically this is angle-dependent and should be between 1/2 and sqrt(2)/2, but this works.
  359. return distance2 <= (radius2 + radius + 0.25) && distance2 >= (radius2 - radius + 0.25);
  360. };
  361. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  362. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  363. for (int i = rect.height() - 1; i >= 0; --i) {
  364. for (int j = 0; j < rect.width(); ++j)
  365. if (is_on_arc(j, rect.height() - i + clip_offset))
  366. dst[j] = Color::from_argb(dst[j]).blend(color).value();
  367. dst += dst_skip;
  368. }
  369. return draw_circle_arc_intersecting(a_rect, center, radius - 1, color, thickness - 1);
  370. }
  371. // The callback will only be called for a quarter of the ellipse, the user is intended to deduce other points.
  372. // As the coordinate space is relative to the center of the rectangle, it's simply (x, y), (x, -y), (-x, y) and (-x, -y).
  373. static void on_each_ellipse_point(IntRect const& rect, Function<void(IntPoint)>&& callback)
  374. {
  375. // Note: This is an implementation of the Midpoint Ellipse Algorithm.
  376. double const a = rect.width() / 2;
  377. double const a_square = a * a;
  378. double const b = rect.height() / 2;
  379. double const b_square = b * b;
  380. int x = 0;
  381. auto y = static_cast<int>(b);
  382. double dx = 2 * b_square * x;
  383. double dy = 2 * a_square * y;
  384. // For region 1:
  385. auto decision_parameter = b_square - a_square * b + .25 * a_square;
  386. while (dx < dy) {
  387. callback({ x, y });
  388. if (decision_parameter >= 0) {
  389. y--;
  390. dy -= 2 * a_square;
  391. decision_parameter -= dy;
  392. }
  393. x++;
  394. dx += 2 * b_square;
  395. decision_parameter += dx + b_square;
  396. }
  397. // For region 2:
  398. decision_parameter = b_square * ((x + 0.5) * (x + 0.5)) + a_square * ((y - 1) * (y - 1)) - a_square * b_square;
  399. while (y >= 0) {
  400. callback({ x, y });
  401. if (decision_parameter <= 0) {
  402. x++;
  403. dx += 2 * b_square;
  404. decision_parameter += dx;
  405. }
  406. y--;
  407. dy -= 2 * a_square;
  408. decision_parameter += a_square - dy;
  409. }
  410. }
  411. void Painter::fill_ellipse(IntRect const& a_rect, Color color)
  412. {
  413. VERIFY(scale() == 1); // FIXME: Add scaling support.
  414. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  415. if (rect.is_empty())
  416. return;
  417. VERIFY(m_target->rect().contains(rect));
  418. auto const center = a_rect.center();
  419. on_each_ellipse_point(rect, [this, &color, center](IntPoint position) {
  420. IntPoint const directions[4] = { { position.x(), position.y() }, { -position.x(), position.y() }, { position.x(), -position.y() }, { -position.x(), -position.y() } };
  421. draw_line(center + directions[0], center + directions[1], color);
  422. draw_line(center + directions[2], center + directions[3], color);
  423. });
  424. }
  425. void Painter::draw_ellipse_intersecting(IntRect const& rect, Color color, int thickness)
  426. {
  427. VERIFY(scale() == 1); // FIXME: Add scaling support.
  428. if (thickness <= 0)
  429. return;
  430. auto const center = rect.center();
  431. on_each_ellipse_point(rect, [this, &color, thickness, center](IntPoint position) {
  432. IntPoint const directions[4] = { { position.x(), position.y() }, { position.x(), -position.y() }, { -position.x(), position.y() }, { -position.x(), -position.y() } };
  433. for (auto const delta : directions) {
  434. auto const point = center + delta;
  435. draw_line(point, point, color, thickness);
  436. }
  437. });
  438. }
  439. template<typename RectType, typename Callback>
  440. static void for_each_pixel_around_rect_clockwise(RectType const& rect, Callback callback)
  441. {
  442. if (rect.is_empty())
  443. return;
  444. for (auto x = rect.left(); x <= rect.right(); ++x) {
  445. callback(x, rect.top());
  446. }
  447. for (auto y = rect.top() + 1; y <= rect.bottom(); ++y) {
  448. callback(rect.right(), y);
  449. }
  450. for (auto x = rect.right() - 1; x >= rect.left(); --x) {
  451. callback(x, rect.bottom());
  452. }
  453. for (auto y = rect.bottom() - 1; y > rect.top(); --y) {
  454. callback(rect.left(), y);
  455. }
  456. }
  457. void Painter::draw_focus_rect(IntRect const& rect, Color color)
  458. {
  459. VERIFY(scale() == 1); // FIXME: Add scaling support.
  460. if (rect.is_empty())
  461. return;
  462. bool state = false;
  463. for_each_pixel_around_rect_clockwise(rect, [&](auto x, auto y) {
  464. if (state)
  465. set_pixel(x, y, color);
  466. state = !state;
  467. });
  468. }
  469. void Painter::draw_rect(IntRect const& a_rect, Color color, bool rough)
  470. {
  471. IntRect rect = a_rect.translated(translation());
  472. auto clipped_rect = rect.intersected(clip_rect());
  473. if (clipped_rect.is_empty())
  474. return;
  475. int min_y = clipped_rect.top();
  476. int max_y = clipped_rect.bottom();
  477. int scale = this->scale();
  478. if (rect.top() >= clipped_rect.top() && rect.top() <= clipped_rect.bottom()) {
  479. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  480. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  481. for (int i = 0; i < scale; ++i)
  482. fill_physical_scanline_with_draw_op(rect.top() * scale + i, start_x * scale, width * scale, color);
  483. ++min_y;
  484. }
  485. if (rect.bottom() >= clipped_rect.top() && rect.bottom() <= clipped_rect.bottom()) {
  486. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  487. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  488. for (int i = 0; i < scale; ++i)
  489. fill_physical_scanline_with_draw_op(max_y * scale + i, start_x * scale, width * scale, color);
  490. --max_y;
  491. }
  492. bool draw_left_side = rect.left() >= clipped_rect.left();
  493. bool draw_right_side = rect.right() == clipped_rect.right();
  494. if (draw_left_side && draw_right_side) {
  495. // Specialized loop when drawing both sides.
  496. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  497. auto* bits = m_target->scanline(y);
  498. for (int i = 0; i < scale; ++i)
  499. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  500. for (int i = 0; i < scale; ++i)
  501. set_physical_pixel_with_draw_op(bits[rect.right() * scale + i], color);
  502. }
  503. } else {
  504. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  505. auto* bits = m_target->scanline(y);
  506. if (draw_left_side)
  507. for (int i = 0; i < scale; ++i)
  508. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  509. if (draw_right_side)
  510. for (int i = 0; i < scale; ++i)
  511. set_physical_pixel_with_draw_op(bits[rect.right() * scale + i], color);
  512. }
  513. }
  514. }
  515. void Painter::draw_rect_with_thickness(IntRect const& rect, Color color, int thickness)
  516. {
  517. if (thickness <= 0)
  518. return;
  519. IntPoint p1 = rect.location();
  520. IntPoint p2 = { rect.location().x() + rect.width(), rect.location().y() };
  521. IntPoint p3 = { rect.location().x() + rect.width(), rect.location().y() + rect.height() };
  522. IntPoint p4 = { rect.location().x(), rect.location().y() + rect.height() };
  523. draw_line(p1, p2, color, thickness);
  524. draw_line(p2, p3, color, thickness);
  525. draw_line(p3, p4, color, thickness);
  526. draw_line(p4, p1, color, thickness);
  527. }
  528. void Painter::draw_bitmap(IntPoint p, CharacterBitmap const& bitmap, Color color)
  529. {
  530. VERIFY(scale() == 1); // FIXME: Add scaling support.
  531. auto rect = IntRect(p, bitmap.size()).translated(translation());
  532. auto clipped_rect = rect.intersected(clip_rect());
  533. if (clipped_rect.is_empty())
  534. return;
  535. int const first_row = clipped_rect.top() - rect.top();
  536. int const last_row = clipped_rect.bottom() - rect.top();
  537. int const first_column = clipped_rect.left() - rect.left();
  538. int const last_column = clipped_rect.right() - rect.left();
  539. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  540. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  541. char const* bitmap_row = &bitmap.bits()[first_row * bitmap.width() + first_column];
  542. size_t const bitmap_skip = bitmap.width();
  543. for (int row = first_row; row <= last_row; ++row) {
  544. for (int j = 0; j <= (last_column - first_column); ++j) {
  545. char fc = bitmap_row[j];
  546. if (fc == '#')
  547. dst[j] = color.value();
  548. }
  549. bitmap_row += bitmap_skip;
  550. dst += dst_skip;
  551. }
  552. }
  553. void Painter::draw_bitmap(IntPoint p, GlyphBitmap const& bitmap, Color color)
  554. {
  555. auto dst_rect = IntRect(p, bitmap.size()).translated(translation());
  556. auto clipped_rect = dst_rect.intersected(clip_rect());
  557. if (clipped_rect.is_empty())
  558. return;
  559. int const first_row = clipped_rect.top() - dst_rect.top();
  560. int const last_row = clipped_rect.bottom() - dst_rect.top();
  561. int const first_column = clipped_rect.left() - dst_rect.left();
  562. int const last_column = clipped_rect.right() - dst_rect.left();
  563. int scale = this->scale();
  564. ARGB32* dst = m_target->scanline(clipped_rect.y() * scale) + clipped_rect.x() * scale;
  565. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  566. if (scale == 1) {
  567. for (int row = first_row; row <= last_row; ++row) {
  568. for (int j = 0; j <= (last_column - first_column); ++j) {
  569. if (bitmap.bit_at(j + first_column, row))
  570. dst[j] = Color::from_argb(dst[j]).blend(color).value();
  571. }
  572. dst += dst_skip;
  573. }
  574. } else {
  575. for (int row = first_row; row <= last_row; ++row) {
  576. for (int j = 0; j <= (last_column - first_column); ++j) {
  577. if (bitmap.bit_at((j + first_column), row)) {
  578. for (int iy = 0; iy < scale; ++iy)
  579. for (int ix = 0; ix < scale; ++ix) {
  580. auto pixel_index = j * scale + ix + iy * dst_skip;
  581. dst[pixel_index] = Color::from_argb(dst[pixel_index]).blend(color).value();
  582. }
  583. }
  584. }
  585. dst += dst_skip * scale;
  586. }
  587. }
  588. }
  589. void Painter::draw_triangle(IntPoint offset, Span<IntPoint const> control_points, Color color)
  590. {
  591. VERIFY(control_points.size() == 3);
  592. draw_triangle(control_points[0] + offset, control_points[1] + offset, control_points[2] + offset, color);
  593. }
  594. void Painter::draw_triangle(IntPoint a, IntPoint b, IntPoint c, Color color)
  595. {
  596. IntPoint p0(to_physical(a));
  597. IntPoint p1(to_physical(b));
  598. IntPoint p2(to_physical(c));
  599. // sort points from top to bottom
  600. if (p0.y() > p1.y())
  601. swap(p0, p1);
  602. if (p0.y() > p2.y())
  603. swap(p0, p2);
  604. if (p1.y() > p2.y())
  605. swap(p1, p2);
  606. // return if top and bottom points are on same line
  607. if (p0.y() == p2.y())
  608. return;
  609. // return if all points are on the same line vertically
  610. if (p0.x() == p1.x() && p1.x() == p2.x())
  611. return;
  612. // return if top is below clip rect or bottom is above clip rect
  613. auto clip = clip_rect();
  614. if (p0.y() >= clip.bottom())
  615. return;
  616. if (p2.y() < clip.top())
  617. return;
  618. class BoundaryLine {
  619. private:
  620. IntPoint m_base {};
  621. IntPoint m_path {};
  622. public:
  623. BoundaryLine(IntPoint a, IntPoint b)
  624. {
  625. VERIFY(a.y() <= b.y());
  626. m_base = a;
  627. m_path = b - a;
  628. }
  629. int top_y() const { return m_base.y(); }
  630. int bottom_y() const { return m_base.y() + m_path.y(); }
  631. bool is_vertical() const { return m_path.x() == 0; }
  632. bool is_horizontal() const { return m_path.y() == 0; }
  633. bool in_y_range(int y) const { return y >= top_y() && y <= bottom_y(); }
  634. Optional<int> intersection_on_x(int y) const
  635. {
  636. if (!in_y_range(y))
  637. return {};
  638. if (is_horizontal())
  639. return {};
  640. if (is_vertical())
  641. return m_base.x();
  642. int y_diff = y - top_y();
  643. int x_d = m_path.x() * y_diff, y_d = m_path.y();
  644. return (x_d / y_d) + m_base.x();
  645. }
  646. };
  647. BoundaryLine l0(p0, p1), l1(p0, p2), l2(p1, p2);
  648. int rgba = color.value();
  649. for (int y = max(p0.y(), clip.top()); y <= min(p2.y(), clip.bottom()); y++) {
  650. Optional<int>
  651. x0 = l0.intersection_on_x(y),
  652. x1 = l1.intersection_on_x(y),
  653. x2 = l2.intersection_on_x(y);
  654. int result_a = 0, result_b = 0;
  655. if (x0.has_value()) {
  656. result_a = x0.value();
  657. if (x1.has_value() && ((!x2.has_value()) || (result_a != x1.value()))) {
  658. result_b = x1.value();
  659. } else {
  660. result_b = x2.value();
  661. }
  662. } else if (x1.has_value()) {
  663. result_a = x1.value();
  664. result_b = x2.value();
  665. }
  666. if (result_a > result_b)
  667. swap(result_a, result_b);
  668. int left_bound = result_a, right_bound = result_b;
  669. ARGB32* scanline = m_target->scanline(y);
  670. for (int x = max(left_bound, clip.left()); x <= min(right_bound, clip.right()); x++) {
  671. scanline[x] = rgba;
  672. }
  673. }
  674. }
  675. struct BlitState {
  676. enum AlphaState {
  677. NoAlpha = 0,
  678. SrcAlpha = 1,
  679. DstAlpha = 2,
  680. BothAlpha = SrcAlpha | DstAlpha
  681. };
  682. ARGB32 const* src;
  683. ARGB32* dst;
  684. size_t src_pitch;
  685. size_t dst_pitch;
  686. int row_count;
  687. int column_count;
  688. float opacity;
  689. BitmapFormat src_format;
  690. };
  691. // FIXME: This is a hack to support blit_with_opacity() with RGBA8888 source.
  692. // Ideally we'd have a more generic solution that allows any source format.
  693. static void swap_red_and_blue_channels(Color& color)
  694. {
  695. u32 rgba = color.value();
  696. u32 bgra = (rgba & 0xff00ff00)
  697. | ((rgba & 0x000000ff) << 16)
  698. | ((rgba & 0x00ff0000) >> 16);
  699. color = Color::from_argb(bgra);
  700. }
  701. // FIXME: This function is very unoptimized.
  702. template<BlitState::AlphaState has_alpha>
  703. static void do_blit_with_opacity(BlitState& state)
  704. {
  705. for (int row = 0; row < state.row_count; ++row) {
  706. for (int x = 0; x < state.column_count; ++x) {
  707. Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_argb(state.dst[x]) : Color::from_rgb(state.dst[x]);
  708. if constexpr (has_alpha & BlitState::SrcAlpha) {
  709. Color src_color_with_alpha = Color::from_argb(state.src[x]);
  710. if (state.src_format == BitmapFormat::RGBA8888)
  711. swap_red_and_blue_channels(src_color_with_alpha);
  712. float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
  713. src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
  714. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  715. } else {
  716. Color src_color_with_alpha = Color::from_rgb(state.src[x]);
  717. if (state.src_format == BitmapFormat::RGBA8888)
  718. swap_red_and_blue_channels(src_color_with_alpha);
  719. src_color_with_alpha.set_alpha(state.opacity * 255);
  720. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  721. }
  722. }
  723. state.dst += state.dst_pitch;
  724. state.src += state.src_pitch;
  725. }
  726. }
  727. void Painter::blit_with_opacity(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  728. {
  729. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  730. if (opacity >= 1.0f && !(source.has_alpha_channel() && apply_alpha))
  731. return blit(position, source, a_src_rect);
  732. IntRect safe_src_rect = IntRect::intersection(a_src_rect, source.rect());
  733. if (scale() != source.scale())
  734. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  735. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  736. auto clipped_rect = dst_rect.intersected(clip_rect());
  737. if (clipped_rect.is_empty())
  738. return;
  739. int scale = this->scale();
  740. auto src_rect = a_src_rect * scale;
  741. clipped_rect *= scale;
  742. dst_rect *= scale;
  743. int const first_row = clipped_rect.top() - dst_rect.top();
  744. int const last_row = clipped_rect.bottom() - dst_rect.top();
  745. int const first_column = clipped_rect.left() - dst_rect.left();
  746. int const last_column = clipped_rect.right() - dst_rect.left();
  747. BlitState blit_state {
  748. .src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column,
  749. .dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x(),
  750. .src_pitch = source.pitch() / sizeof(ARGB32),
  751. .dst_pitch = m_target->pitch() / sizeof(ARGB32),
  752. .row_count = last_row - first_row + 1,
  753. .column_count = last_column - first_column + 1,
  754. .opacity = opacity,
  755. .src_format = source.format(),
  756. };
  757. if (source.has_alpha_channel() && apply_alpha) {
  758. if (m_target->has_alpha_channel())
  759. do_blit_with_opacity<BlitState::BothAlpha>(blit_state);
  760. else
  761. do_blit_with_opacity<BlitState::SrcAlpha>(blit_state);
  762. } else {
  763. if (m_target->has_alpha_channel())
  764. do_blit_with_opacity<BlitState::DstAlpha>(blit_state);
  765. else
  766. do_blit_with_opacity<BlitState::NoAlpha>(blit_state);
  767. }
  768. }
  769. void Painter::blit_filtered(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, Function<Color(Color)> filter)
  770. {
  771. VERIFY((source.scale() == 1 || source.scale() == scale()) && "blit_filtered only supports integer upsampling");
  772. IntRect safe_src_rect = src_rect.intersected(source.rect());
  773. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  774. auto clipped_rect = dst_rect.intersected(clip_rect());
  775. if (clipped_rect.is_empty())
  776. return;
  777. int scale = this->scale();
  778. clipped_rect *= scale;
  779. dst_rect *= scale;
  780. safe_src_rect *= source.scale();
  781. int const first_row = clipped_rect.top() - dst_rect.top();
  782. int const last_row = clipped_rect.bottom() - dst_rect.top();
  783. int const first_column = clipped_rect.left() - dst_rect.left();
  784. int const last_column = clipped_rect.right() - dst_rect.left();
  785. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  786. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  787. int s = scale / source.scale();
  788. if (s == 1) {
  789. ARGB32 const* src = source.scanline(safe_src_rect.top() + first_row) + safe_src_rect.left() + first_column;
  790. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  791. for (int row = first_row; row <= last_row; ++row) {
  792. for (int x = 0; x <= (last_column - first_column); ++x) {
  793. u8 alpha = Color::from_argb(src[x]).alpha();
  794. if (alpha == 0xff) {
  795. auto color = filter(Color::from_argb(src[x]));
  796. if (color.alpha() == 0xff)
  797. dst[x] = color.value();
  798. else
  799. dst[x] = Color::from_argb(dst[x]).blend(color).value();
  800. } else if (!alpha)
  801. continue;
  802. else
  803. dst[x] = Color::from_argb(dst[x]).blend(filter(Color::from_argb(src[x]))).value();
  804. }
  805. dst += dst_skip;
  806. src += src_skip;
  807. }
  808. } else {
  809. for (int row = first_row; row <= last_row; ++row) {
  810. ARGB32 const* src = source.scanline(safe_src_rect.top() + row / s) + safe_src_rect.left() + first_column / s;
  811. for (int x = 0; x <= (last_column - first_column); ++x) {
  812. u8 alpha = Color::from_argb(src[x / s]).alpha();
  813. if (alpha == 0xff) {
  814. auto color = filter(Color::from_argb(src[x / s]));
  815. if (color.alpha() == 0xff)
  816. dst[x] = color.value();
  817. else
  818. dst[x] = Color::from_argb(dst[x]).blend(color).value();
  819. } else if (!alpha)
  820. continue;
  821. else
  822. dst[x] = Color::from_argb(dst[x]).blend(filter(Color::from_argb(src[x / s]))).value();
  823. }
  824. dst += dst_skip;
  825. }
  826. }
  827. }
  828. void Painter::blit_brightened(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  829. {
  830. return blit_filtered(position, source, src_rect, [](Color src) {
  831. return src.lightened();
  832. });
  833. }
  834. void Painter::blit_dimmed(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  835. {
  836. return blit_filtered(position, source, src_rect, [](Color src) {
  837. return src.to_grayscale().lightened();
  838. });
  839. }
  840. void Painter::draw_tiled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source)
  841. {
  842. VERIFY((source.scale() == 1 || source.scale() == scale()) && "draw_tiled_bitmap only supports integer upsampling");
  843. auto dst_rect = a_dst_rect.translated(translation());
  844. auto clipped_rect = dst_rect.intersected(clip_rect());
  845. if (clipped_rect.is_empty())
  846. return;
  847. int scale = this->scale();
  848. clipped_rect *= scale;
  849. dst_rect *= scale;
  850. int const first_row = (clipped_rect.top() - dst_rect.top());
  851. int const last_row = (clipped_rect.bottom() - dst_rect.top());
  852. int const first_column = (clipped_rect.left() - dst_rect.left());
  853. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  854. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  855. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  856. int s = scale / source.scale();
  857. if (s == 1) {
  858. int x_start = first_column + a_dst_rect.left() * scale;
  859. for (int row = first_row; row <= last_row; ++row) {
  860. ARGB32 const* sl = source.scanline((row + a_dst_rect.top() * scale) % source.physical_height());
  861. for (int x = x_start; x < clipped_rect.width() + x_start; ++x) {
  862. dst[x - x_start] = sl[x % source.physical_width()];
  863. }
  864. dst += dst_skip;
  865. }
  866. } else {
  867. int x_start = first_column + a_dst_rect.left() * scale;
  868. for (int row = first_row; row <= last_row; ++row) {
  869. ARGB32 const* sl = source.scanline(((row + a_dst_rect.top() * scale) / s) % source.physical_height());
  870. for (int x = x_start; x < clipped_rect.width() + x_start; ++x) {
  871. dst[x - x_start] = sl[(x / s) % source.physical_width()];
  872. }
  873. dst += dst_skip;
  874. }
  875. }
  876. return;
  877. }
  878. VERIFY_NOT_REACHED();
  879. }
  880. void Painter::blit_offset(IntPoint a_position, Gfx::Bitmap const& source, IntRect const& a_src_rect, IntPoint offset)
  881. {
  882. auto src_rect = IntRect { a_src_rect.location() - offset, a_src_rect.size() };
  883. auto position = a_position;
  884. if (src_rect.x() < 0) {
  885. position.set_x(position.x() - src_rect.x());
  886. src_rect.set_x(0);
  887. }
  888. if (src_rect.y() < 0) {
  889. position.set_y(position.y() - src_rect.y());
  890. src_rect.set_y(0);
  891. }
  892. blit(position, source, src_rect);
  893. }
  894. void Painter::blit(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  895. {
  896. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  897. if (opacity < 1.0f || (source.has_alpha_channel() && apply_alpha))
  898. return blit_with_opacity(position, source, a_src_rect, opacity, apply_alpha);
  899. auto safe_src_rect = a_src_rect.intersected(source.rect());
  900. if (scale() != source.scale())
  901. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  902. // If we get here, the Painter might have a scale factor, but the source bitmap has the same scale factor.
  903. // We need to transform from logical to physical coordinates, but we can just copy pixels without resampling.
  904. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  905. auto clipped_rect = dst_rect.intersected(clip_rect());
  906. if (clipped_rect.is_empty())
  907. return;
  908. // All computations below are in physical coordinates.
  909. int scale = this->scale();
  910. auto src_rect = a_src_rect * scale;
  911. clipped_rect *= scale;
  912. dst_rect *= scale;
  913. int const first_row = clipped_rect.top() - dst_rect.top();
  914. int const last_row = clipped_rect.bottom() - dst_rect.top();
  915. int const first_column = clipped_rect.left() - dst_rect.left();
  916. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  917. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  918. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  919. ARGB32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  920. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  921. for (int row = first_row; row <= last_row; ++row) {
  922. memcpy(dst, src, sizeof(ARGB32) * clipped_rect.width());
  923. dst += dst_skip;
  924. src += src_skip;
  925. }
  926. return;
  927. }
  928. if (source.format() == BitmapFormat::RGBA8888) {
  929. u32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  930. size_t const src_skip = source.pitch() / sizeof(u32);
  931. for (int row = first_row; row <= last_row; ++row) {
  932. for (int i = 0; i < clipped_rect.width(); ++i) {
  933. u32 rgba = src[i];
  934. u32 bgra = (rgba & 0xff00ff00)
  935. | ((rgba & 0x000000ff) << 16)
  936. | ((rgba & 0x00ff0000) >> 16);
  937. dst[i] = bgra;
  938. }
  939. dst += dst_skip;
  940. src += src_skip;
  941. }
  942. return;
  943. }
  944. if (Bitmap::is_indexed(source.format())) {
  945. u8 const* src = source.scanline_u8(src_rect.top() + first_row) + src_rect.left() + first_column;
  946. size_t const src_skip = source.pitch();
  947. for (int row = first_row; row <= last_row; ++row) {
  948. for (int i = 0; i < clipped_rect.width(); ++i)
  949. dst[i] = source.palette_color(src[i]).value();
  950. dst += dst_skip;
  951. src += src_skip;
  952. }
  953. return;
  954. }
  955. VERIFY_NOT_REACHED();
  956. }
  957. template<bool has_alpha_channel, typename GetPixel>
  958. 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)
  959. {
  960. int x_limit = min(target.physical_width() - 1, dst_rect.right());
  961. int y_limit = min(target.physical_height() - 1, dst_rect.bottom());
  962. bool has_opacity = opacity != 1.0f;
  963. for (int y = 0; y < src_rect.height(); ++y) {
  964. int dst_y = dst_rect.y() + y * vfactor;
  965. for (int x = 0; x < src_rect.width(); ++x) {
  966. auto src_pixel = get_pixel(source, x + src_rect.left(), y + src_rect.top());
  967. if (has_opacity)
  968. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  969. for (int yo = 0; yo < vfactor && dst_y + yo <= y_limit; ++yo) {
  970. auto* scanline = (Color*)target.scanline(dst_y + yo);
  971. int dst_x = dst_rect.x() + x * hfactor;
  972. for (int xo = 0; xo < hfactor && dst_x + xo <= x_limit; ++xo) {
  973. if constexpr (has_alpha_channel)
  974. scanline[dst_x + xo] = scanline[dst_x + xo].blend(src_pixel);
  975. else
  976. scanline[dst_x + xo] = src_pixel;
  977. }
  978. }
  979. }
  980. }
  981. }
  982. template<bool has_alpha_channel, Painter::ScalingMode scaling_mode, typename GetPixel>
  983. 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)
  984. {
  985. auto int_src_rect = enclosing_int_rect(src_rect);
  986. auto clipped_src_rect = int_src_rect.intersected(source.rect());
  987. if (clipped_src_rect.is_empty())
  988. return;
  989. if (scaling_mode == Painter::ScalingMode::NearestFractional) {
  990. int hfactor = (dst_rect.width() + int_src_rect.width() - 1) / int_src_rect.width();
  991. int vfactor = (dst_rect.height() + int_src_rect.height() - 1) / int_src_rect.height();
  992. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  993. }
  994. if constexpr (scaling_mode == Painter::ScalingMode::NearestNeighbor || scaling_mode == Painter::ScalingMode::SmoothPixels) {
  995. if (dst_rect == clipped_rect && int_src_rect == src_rect && !(dst_rect.width() % int_src_rect.width()) && !(dst_rect.height() % int_src_rect.height())) {
  996. int hfactor = dst_rect.width() / int_src_rect.width();
  997. int vfactor = dst_rect.height() / int_src_rect.height();
  998. if (hfactor == 2 && vfactor == 2)
  999. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 2, 2, get_pixel, opacity);
  1000. if (hfactor == 3 && vfactor == 3)
  1001. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 3, 3, get_pixel, opacity);
  1002. if (hfactor == 4 && vfactor == 4)
  1003. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 4, 4, get_pixel, opacity);
  1004. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  1005. }
  1006. }
  1007. bool has_opacity = opacity != 1.0f;
  1008. i64 shift = (i64)1 << 32;
  1009. i64 fractional_mask = (shift - (u64)1);
  1010. i64 bilinear_offset_x = (1ll << 31) * (src_rect.width() / dst_rect.width() - 1);
  1011. i64 bilinear_offset_y = (1ll << 31) * (src_rect.height() / dst_rect.height() - 1);
  1012. i64 hscale = (src_rect.width() * shift) / dst_rect.width();
  1013. i64 vscale = (src_rect.height() * shift) / dst_rect.height();
  1014. i64 src_left = src_rect.left() * shift;
  1015. i64 src_top = src_rect.top() * shift;
  1016. i64 clipped_src_bottom_shifted = (clipped_src_rect.y() + clipped_src_rect.height()) * shift;
  1017. i64 clipped_src_right_shifted = (clipped_src_rect.x() + clipped_src_rect.width()) * shift;
  1018. for (int y = clipped_rect.top(); y <= clipped_rect.bottom(); ++y) {
  1019. auto* scanline = (Color*)target.scanline(y);
  1020. auto desired_y = ((y - dst_rect.y()) * vscale + src_top);
  1021. if (desired_y < clipped_src_rect.top() || desired_y > clipped_src_bottom_shifted)
  1022. continue;
  1023. for (int x = clipped_rect.left(); x <= clipped_rect.right(); ++x) {
  1024. auto desired_x = ((x - dst_rect.x()) * hscale + src_left);
  1025. if (desired_x < clipped_src_rect.left() || desired_x > clipped_src_right_shifted)
  1026. continue;
  1027. Color src_pixel;
  1028. if constexpr (scaling_mode == Painter::ScalingMode::BilinearBlend) {
  1029. auto shifted_x = desired_x + bilinear_offset_x;
  1030. auto shifted_y = desired_y + bilinear_offset_y;
  1031. auto scaled_x0 = clamp(shifted_x >> 32, clipped_src_rect.left(), clipped_src_rect.right());
  1032. auto scaled_x1 = clamp((shifted_x >> 32) + 1, clipped_src_rect.left(), clipped_src_rect.right());
  1033. auto scaled_y0 = clamp(shifted_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom());
  1034. auto scaled_y1 = clamp((shifted_y >> 32) + 1, clipped_src_rect.top(), clipped_src_rect.bottom());
  1035. float x_ratio = (shifted_x & fractional_mask) / static_cast<float>(shift);
  1036. float y_ratio = (shifted_y & fractional_mask) / static_cast<float>(shift);
  1037. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1038. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1039. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1040. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1041. auto top = top_left.interpolate(top_right, x_ratio);
  1042. auto bottom = bottom_left.interpolate(bottom_right, x_ratio);
  1043. src_pixel = top.interpolate(bottom, y_ratio);
  1044. } else if constexpr (scaling_mode == Painter::ScalingMode::SmoothPixels) {
  1045. auto scaled_x1 = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right());
  1046. auto scaled_x0 = clamp(scaled_x1 - 1, clipped_src_rect.left(), clipped_src_rect.right());
  1047. auto scaled_y1 = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom());
  1048. auto scaled_y0 = clamp(scaled_y1 - 1, clipped_src_rect.top(), clipped_src_rect.bottom());
  1049. float x_ratio = (desired_x & fractional_mask) / (float)shift;
  1050. float y_ratio = (desired_y & fractional_mask) / (float)shift;
  1051. float scaled_x_ratio = clamp(x_ratio * dst_rect.width() / (float)src_rect.width(), 0.0f, 1.0f);
  1052. float scaled_y_ratio = clamp(y_ratio * dst_rect.height() / (float)src_rect.height(), 0.0f, 1.0f);
  1053. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1054. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1055. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1056. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1057. auto top = top_left.interpolate(top_right, scaled_x_ratio);
  1058. auto bottom = bottom_left.interpolate(bottom_right, scaled_x_ratio);
  1059. src_pixel = top.interpolate(bottom, scaled_y_ratio);
  1060. } else {
  1061. auto scaled_x = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right());
  1062. auto scaled_y = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom());
  1063. src_pixel = get_pixel(source, scaled_x, scaled_y);
  1064. }
  1065. if (has_opacity)
  1066. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  1067. if constexpr (has_alpha_channel) {
  1068. scanline[x] = scanline[x].blend(src_pixel);
  1069. } else {
  1070. scanline[x] = src_pixel;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. template<bool has_alpha_channel, typename GetPixel>
  1076. 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, Painter::ScalingMode scaling_mode)
  1077. {
  1078. switch (scaling_mode) {
  1079. case Painter::ScalingMode::NearestFractional:
  1080. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::NearestFractional>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1081. break;
  1082. case Painter::ScalingMode::NearestNeighbor:
  1083. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::NearestNeighbor>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1084. break;
  1085. case Painter::ScalingMode::SmoothPixels:
  1086. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::SmoothPixels>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1087. break;
  1088. case Painter::ScalingMode::BilinearBlend:
  1089. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::BilinearBlend>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1090. break;
  1091. case Painter::ScalingMode::None:
  1092. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::None>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1093. break;
  1094. }
  1095. }
  1096. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1097. {
  1098. draw_scaled_bitmap(a_dst_rect, source, FloatRect { a_src_rect }, opacity, scaling_mode);
  1099. }
  1100. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, FloatRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1101. {
  1102. IntRect int_src_rect = enclosing_int_rect(a_src_rect);
  1103. if (scale() == source.scale() && a_src_rect == int_src_rect && a_dst_rect.size() == int_src_rect.size())
  1104. return blit(a_dst_rect.location(), source, int_src_rect, opacity);
  1105. if (scaling_mode == ScalingMode::None) {
  1106. 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() };
  1107. return blit(a_dst_rect.location(), source, clipped_draw_rect, opacity);
  1108. }
  1109. auto dst_rect = to_physical(a_dst_rect);
  1110. auto src_rect = a_src_rect * source.scale();
  1111. auto clipped_rect = dst_rect.intersected(clip_rect() * scale());
  1112. if (clipped_rect.is_empty())
  1113. return;
  1114. if (source.has_alpha_channel() || opacity != 1.0f) {
  1115. switch (source.format()) {
  1116. case BitmapFormat::BGRx8888:
  1117. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1118. break;
  1119. case BitmapFormat::BGRA8888:
  1120. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRA8888>, opacity, scaling_mode);
  1121. break;
  1122. case BitmapFormat::Indexed8:
  1123. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1124. break;
  1125. case BitmapFormat::Indexed4:
  1126. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed4>, opacity, scaling_mode);
  1127. break;
  1128. case BitmapFormat::Indexed2:
  1129. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed2>, opacity, scaling_mode);
  1130. break;
  1131. case BitmapFormat::Indexed1:
  1132. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed1>, opacity, scaling_mode);
  1133. break;
  1134. default:
  1135. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1136. break;
  1137. }
  1138. } else {
  1139. switch (source.format()) {
  1140. case BitmapFormat::BGRx8888:
  1141. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1142. break;
  1143. case BitmapFormat::Indexed8:
  1144. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1145. break;
  1146. default:
  1147. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1148. break;
  1149. }
  1150. }
  1151. }
  1152. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Color color)
  1153. {
  1154. draw_glyph(point, code_point, font(), color);
  1155. }
  1156. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Font const& font, Color color)
  1157. {
  1158. auto top_left = point + FloatPoint(font.glyph_left_bearing(code_point), 0);
  1159. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  1160. auto glyph = font.glyph(code_point, glyph_position.subpixel_offset);
  1161. if (glyph.is_glyph_bitmap()) {
  1162. draw_bitmap(top_left.to_type<int>(), glyph.glyph_bitmap(), color);
  1163. } else {
  1164. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1165. return pixel.multiply(color);
  1166. });
  1167. }
  1168. }
  1169. void Painter::draw_emoji(IntPoint point, Gfx::Bitmap const& emoji, Font const& font)
  1170. {
  1171. IntRect dst_rect {
  1172. point.x(),
  1173. point.y(),
  1174. static_cast<int>(ceilf(font.pixel_size() * emoji.width() / emoji.height())),
  1175. static_cast<int>(ceilf(font.pixel_size())),
  1176. };
  1177. draw_scaled_bitmap(dst_rect, emoji, emoji.rect());
  1178. }
  1179. void Painter::draw_glyph_or_emoji(FloatPoint point, u32 code_point, Font const& font, Color color)
  1180. {
  1181. StringBuilder builder;
  1182. builder.append_code_point(code_point);
  1183. auto it = Utf8View { builder.string_view() }.begin();
  1184. return draw_glyph_or_emoji(point, it, font, color);
  1185. }
  1186. void Painter::draw_glyph_or_emoji(FloatPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1187. {
  1188. // FIXME: These should live somewhere else.
  1189. constexpr u32 text_variation_selector = 0xFE0E;
  1190. constexpr u32 emoji_variation_selector = 0xFE0F;
  1191. constexpr u32 regional_indicator_symbol_a = 0x1F1E6;
  1192. constexpr u32 regional_indicator_symbol_z = 0x1F1FF;
  1193. auto initial_it = it;
  1194. u32 code_point = *it;
  1195. auto next_code_point = it.peek(1);
  1196. ScopeGuard consume_variation_selector = [&] {
  1197. // If we advanced the iterator to consume an emoji sequence, don't look for another variation selector.
  1198. if (initial_it != it)
  1199. return;
  1200. // Otherwise, discard one code point if it's a variation selector.
  1201. auto next_code_point = it.peek(1);
  1202. if (next_code_point == text_variation_selector || next_code_point == emoji_variation_selector)
  1203. ++it;
  1204. };
  1205. auto code_point_is_regional_indicator = code_point >= regional_indicator_symbol_a && code_point <= regional_indicator_symbol_z;
  1206. auto font_contains_glyph = font.contains_glyph(code_point);
  1207. auto check_for_emoji = false
  1208. // Flag emojis consist of two regional indicators.
  1209. || code_point_is_regional_indicator
  1210. // U+00A9 (copyright) or U+00AE (registered) are text glyphs by default,
  1211. // keycap emojis ({#,*,0-9} U+FE0F U+20E3) start with a regular ASCII character.
  1212. // Both cases are handled by peeking for the variation selector.
  1213. || next_code_point == emoji_variation_selector;
  1214. // If the font contains the glyph, and we know it's not the start of an emoji, draw a text glyph.
  1215. if (font_contains_glyph && !check_for_emoji) {
  1216. draw_glyph(point, code_point, font, color);
  1217. return;
  1218. }
  1219. // If we didn't find a text glyph, or have an emoji variation selector or regional indicator, try to draw an emoji glyph.
  1220. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it)) {
  1221. draw_emoji(point.to_type<int>(), *emoji, font);
  1222. return;
  1223. }
  1224. // If that failed, but we have a text glyph fallback, draw that.
  1225. if (font_contains_glyph) {
  1226. draw_glyph(point, code_point, font, color);
  1227. return;
  1228. }
  1229. // No suitable glyph found, draw a replacement character.
  1230. dbgln_if(EMOJI_DEBUG, "Failed to find a glyph or emoji for code_point {}", code_point);
  1231. draw_glyph(point, 0xFFFD, font, color);
  1232. }
  1233. void Painter::draw_glyph(IntPoint point, u32 code_point, Color color)
  1234. {
  1235. draw_glyph(point.to_type<float>(), code_point, font(), color);
  1236. }
  1237. void Painter::draw_glyph(IntPoint point, u32 code_point, Font const& font, Color color)
  1238. {
  1239. draw_glyph(point.to_type<float>(), code_point, font, color);
  1240. }
  1241. void Painter::draw_glyph_or_emoji(IntPoint point, u32 code_point, Font const& font, Color color)
  1242. {
  1243. draw_glyph_or_emoji(point.to_type<float>(), code_point, font, color);
  1244. }
  1245. void Painter::draw_glyph_or_emoji(IntPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1246. {
  1247. draw_glyph_or_emoji(point.to_type<float>(), it, font, color);
  1248. }
  1249. template<typename DrawGlyphFunction>
  1250. void draw_text_line(FloatRect const& a_rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextDirection direction, DrawGlyphFunction draw_glyph)
  1251. {
  1252. auto rect = a_rect;
  1253. switch (alignment) {
  1254. case TextAlignment::TopLeft:
  1255. case TextAlignment::CenterLeft:
  1256. case TextAlignment::BottomLeft:
  1257. break;
  1258. case TextAlignment::TopRight:
  1259. case TextAlignment::CenterRight:
  1260. case TextAlignment::BottomRight:
  1261. rect.set_x(rect.right() - font.width(text));
  1262. break;
  1263. case TextAlignment::TopCenter:
  1264. case TextAlignment::BottomCenter:
  1265. case TextAlignment::Center: {
  1266. auto shrunken_rect = rect;
  1267. shrunken_rect.set_width(font.width(text));
  1268. shrunken_rect.center_within(rect);
  1269. rect = shrunken_rect;
  1270. break;
  1271. }
  1272. default:
  1273. VERIFY_NOT_REACHED();
  1274. }
  1275. auto point = rect.location();
  1276. auto space_width = font.glyph_width(' ') + font.glyph_spacing();
  1277. if (direction == TextDirection::RTL) {
  1278. point.translate_by(rect.width(), 0); // Start drawing from the end
  1279. space_width = -space_width; // Draw spaces backwards
  1280. }
  1281. u32 last_code_point { 0 };
  1282. for (auto it = text.begin(); it != text.end(); ++it) {
  1283. auto code_point = *it;
  1284. if (should_paint_as_space(code_point)) {
  1285. point.translate_by(space_width, 0);
  1286. last_code_point = code_point;
  1287. continue;
  1288. }
  1289. auto kerning = font.glyphs_horizontal_kerning(last_code_point, code_point);
  1290. if (kerning != 0.0f)
  1291. point.translate_by(direction == TextDirection::LTR ? kerning : -kerning, 0);
  1292. FloatSize glyph_size(font.glyph_or_emoji_width(code_point) + font.glyph_spacing(), font.pixel_size());
  1293. if (direction == TextDirection::RTL)
  1294. point.translate_by(-glyph_size.width(), 0); // If we are drawing right to left, we have to move backwards before drawing the glyph
  1295. draw_glyph({ point, glyph_size }, it);
  1296. if (direction == TextDirection::LTR)
  1297. point.translate_by(glyph_size.width(), 0);
  1298. // The callback function might have exhausted the iterator.
  1299. if (it == text.end())
  1300. break;
  1301. last_code_point = code_point;
  1302. }
  1303. }
  1304. static inline size_t draw_text_get_length(Utf8View const& text)
  1305. {
  1306. return text.byte_length();
  1307. }
  1308. Vector<DirectionalRun> Painter::split_text_into_directional_runs(Utf8View const& text, TextDirection initial_direction)
  1309. {
  1310. // FIXME: This is a *very* simplified version of the UNICODE BIDIRECTIONAL ALGORITHM (https://www.unicode.org/reports/tr9/), that can render most bidirectional text
  1311. // 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.
  1312. // FIXME: Support HTML "dir" attribute (how?)
  1313. u8 paragraph_embedding_level = initial_direction == TextDirection::LTR ? 0 : 1;
  1314. Vector<u8> embedding_levels;
  1315. embedding_levels.ensure_capacity(text.length());
  1316. for (size_t i = 0; i < text.length(); i++)
  1317. embedding_levels.unchecked_append(paragraph_embedding_level);
  1318. // FIXME: Support Explicit Directional Formatting Characters
  1319. Vector<BidirectionalClass> character_classes;
  1320. character_classes.ensure_capacity(text.length());
  1321. for (u32 code_point : text)
  1322. character_classes.unchecked_append(get_char_bidi_class(code_point));
  1323. // resolving weak types
  1324. BidirectionalClass paragraph_class = initial_direction == TextDirection::LTR ? BidirectionalClass::STRONG_LTR : BidirectionalClass::STRONG_RTL;
  1325. for (size_t i = 0; i < character_classes.size(); i++) {
  1326. if (character_classes[i] != BidirectionalClass::WEAK_SEPARATORS)
  1327. continue;
  1328. for (ssize_t j = i - 1; j >= 0; j--) {
  1329. auto character_class = character_classes[j];
  1330. if (character_class != BidirectionalClass::STRONG_RTL && character_class != BidirectionalClass::STRONG_LTR)
  1331. continue;
  1332. character_classes[i] = character_class;
  1333. break;
  1334. }
  1335. if (character_classes[i] == BidirectionalClass::WEAK_SEPARATORS)
  1336. character_classes[i] = paragraph_class;
  1337. }
  1338. // resolving neutral types
  1339. auto left_side = BidirectionalClass::NEUTRAL;
  1340. auto sequence_length = 0;
  1341. for (size_t i = 0; i < character_classes.size(); i++) {
  1342. auto character_class = character_classes[i];
  1343. if (left_side == BidirectionalClass::NEUTRAL) {
  1344. if (character_class != BidirectionalClass::NEUTRAL)
  1345. left_side = character_class;
  1346. else
  1347. character_classes[i] = paragraph_class;
  1348. continue;
  1349. }
  1350. if (character_class != BidirectionalClass::NEUTRAL) {
  1351. BidirectionalClass sequence_class;
  1352. if (bidi_class_to_direction(left_side) == bidi_class_to_direction(character_class)) {
  1353. sequence_class = left_side == BidirectionalClass::STRONG_RTL ? BidirectionalClass::STRONG_RTL : BidirectionalClass::STRONG_LTR;
  1354. } else {
  1355. sequence_class = paragraph_class;
  1356. }
  1357. for (auto j = 0; j < sequence_length; j++) {
  1358. character_classes[i - j - 1] = sequence_class;
  1359. }
  1360. sequence_length = 0;
  1361. left_side = character_class;
  1362. } else {
  1363. sequence_length++;
  1364. }
  1365. }
  1366. for (auto i = 0; i < sequence_length; i++)
  1367. character_classes[character_classes.size() - i - 1] = paragraph_class;
  1368. // resolving implicit levels
  1369. for (size_t i = 0; i < character_classes.size(); i++) {
  1370. auto character_class = character_classes[i];
  1371. if ((embedding_levels[i] % 2) == 0) {
  1372. if (character_class == BidirectionalClass::STRONG_RTL)
  1373. embedding_levels[i] += 1;
  1374. else if (character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1375. embedding_levels[i] += 2;
  1376. } else {
  1377. if (character_class == BidirectionalClass::STRONG_LTR || character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1378. embedding_levels[i] += 1;
  1379. }
  1380. }
  1381. // splitting into runs
  1382. auto run_code_points_start = text.begin();
  1383. auto next_code_points_slice = [&](auto length) {
  1384. Vector<u32> run_code_points;
  1385. run_code_points.ensure_capacity(length);
  1386. for (size_t j = 0; j < length; ++j, ++run_code_points_start)
  1387. run_code_points.unchecked_append(*run_code_points_start);
  1388. return run_code_points;
  1389. };
  1390. Vector<DirectionalRun> runs;
  1391. size_t start = 0;
  1392. u8 level = embedding_levels[0];
  1393. for (size_t i = 1; i < embedding_levels.size(); ++i) {
  1394. if (embedding_levels[i] == level)
  1395. continue;
  1396. auto code_points_slice = next_code_points_slice(i - start);
  1397. runs.append({ move(code_points_slice), level });
  1398. start = i;
  1399. level = embedding_levels[i];
  1400. }
  1401. auto code_points_slice = next_code_points_slice(embedding_levels.size() - start);
  1402. runs.append({ move(code_points_slice), level });
  1403. // reordering resolved levels
  1404. // FIXME: missing special cases for trailing whitespace characters
  1405. u8 minimum_level = 128;
  1406. u8 maximum_level = 0;
  1407. for (auto& run : runs) {
  1408. minimum_level = min(minimum_level, run.embedding_level());
  1409. maximum_level = max(minimum_level, run.embedding_level());
  1410. }
  1411. if ((minimum_level % 2) == 0)
  1412. minimum_level++;
  1413. auto runs_count = runs.size() - 1;
  1414. while (maximum_level <= minimum_level) {
  1415. size_t run_index = 0;
  1416. while (run_index < runs_count) {
  1417. while (run_index < runs_count && runs[run_index].embedding_level() < maximum_level)
  1418. run_index++;
  1419. auto reverse_start = run_index;
  1420. while (run_index <= runs_count && runs[run_index].embedding_level() >= maximum_level)
  1421. run_index++;
  1422. auto reverse_end = run_index - 1;
  1423. while (reverse_start < reverse_end) {
  1424. swap(runs[reverse_start], runs[reverse_end]);
  1425. reverse_start++;
  1426. reverse_end--;
  1427. }
  1428. }
  1429. maximum_level--;
  1430. }
  1431. // mirroring RTL mirror characters
  1432. for (auto& run : runs) {
  1433. if (run.direction() == TextDirection::LTR)
  1434. continue;
  1435. for (auto& code_point : run.code_points()) {
  1436. code_point = get_mirror_char(code_point);
  1437. }
  1438. }
  1439. return runs;
  1440. }
  1441. bool Painter::text_contains_bidirectional_text(Utf8View const& text, TextDirection initial_direction)
  1442. {
  1443. for (u32 code_point : text) {
  1444. auto char_class = get_char_bidi_class(code_point);
  1445. if (char_class == BidirectionalClass::NEUTRAL)
  1446. continue;
  1447. if (bidi_class_to_direction(char_class) != initial_direction)
  1448. return true;
  1449. }
  1450. return false;
  1451. }
  1452. template<typename DrawGlyphFunction>
  1453. void Painter::do_draw_text(FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping, DrawGlyphFunction draw_glyph)
  1454. {
  1455. if (draw_text_get_length(text) == 0)
  1456. return;
  1457. TextLayout layout(font, text, rect);
  1458. auto line_height = font.preferred_line_height();
  1459. auto lines = layout.lines(elision, wrapping);
  1460. auto bounding_rect = layout.bounding_rect(wrapping);
  1461. bounding_rect.align_within(rect, alignment);
  1462. for (size_t i = 0; i < lines.size(); ++i) {
  1463. auto line = Utf8View { lines[i] };
  1464. FloatRect line_rect { bounding_rect.x(), bounding_rect.y() + i * line_height, bounding_rect.width(), line_height };
  1465. TextDirection line_direction = get_text_direction(line);
  1466. if (text_contains_bidirectional_text(line, line_direction)) { // Slow Path: The line contains mixed BiDi classes
  1467. auto directional_runs = split_text_into_directional_runs(line, line_direction);
  1468. auto current_dx = line_direction == TextDirection::LTR ? 0 : line_rect.width();
  1469. for (auto& directional_run : directional_runs) {
  1470. auto run_width = font.width(directional_run.text());
  1471. if (line_direction == TextDirection::RTL)
  1472. current_dx -= run_width;
  1473. auto run_rect = line_rect.translated(current_dx, 0);
  1474. run_rect.set_width(run_width);
  1475. // NOTE: DirectionalRun returns Utf32View which isn't
  1476. // compatible with draw_text_line.
  1477. StringBuilder builder;
  1478. builder.append(directional_run.text());
  1479. auto line_text = Utf8View { builder.string_view() };
  1480. draw_text_line(run_rect, line_text, font, alignment, directional_run.direction(), draw_glyph);
  1481. if (line_direction == TextDirection::LTR)
  1482. current_dx += run_width;
  1483. }
  1484. } else {
  1485. draw_text_line(line_rect, line, font, alignment, line_direction, draw_glyph);
  1486. }
  1487. }
  1488. }
  1489. void Painter::draw_text(FloatRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1490. {
  1491. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1492. }
  1493. void Painter::draw_text(FloatRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1494. {
  1495. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1496. }
  1497. void Painter::draw_text(FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1498. {
  1499. Utf8View text { raw_text };
  1500. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1501. draw_glyph_or_emoji(r.location(), it, font, color);
  1502. });
  1503. }
  1504. void Painter::draw_text(FloatRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1505. {
  1506. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1507. // being some places might depend on it, so we do some internal conversion.
  1508. StringBuilder builder;
  1509. builder.append(raw_text);
  1510. auto text = Utf8View { builder.string_view() };
  1511. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1512. draw_glyph_or_emoji(r.location(), it, font, color);
  1513. });
  1514. }
  1515. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1516. {
  1517. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1518. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1519. draw_one_glyph(r, it);
  1520. });
  1521. }
  1522. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1523. {
  1524. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1525. Utf8View text { raw_text };
  1526. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1527. draw_one_glyph(r, it);
  1528. });
  1529. }
  1530. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1531. {
  1532. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1533. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1534. // being some places might depend on it, so we do some internal conversion.
  1535. StringBuilder builder;
  1536. builder.append(raw_text);
  1537. auto text = Utf8View { builder.string_view() };
  1538. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1539. draw_one_glyph(r, it);
  1540. });
  1541. }
  1542. void Painter::draw_text(IntRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1543. {
  1544. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1545. }
  1546. void Painter::draw_text(IntRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1547. {
  1548. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1549. }
  1550. void Painter::draw_text(IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1551. {
  1552. draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1553. }
  1554. void Painter::draw_text(IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1555. {
  1556. return draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1557. }
  1558. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1559. {
  1560. return draw_text(move(draw_one_glyph), rect.to_type<float>(), text, font, alignment, elision, wrapping);
  1561. }
  1562. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1563. {
  1564. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1565. }
  1566. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1567. {
  1568. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1569. }
  1570. void Painter::set_pixel(IntPoint p, Color color, bool blend)
  1571. {
  1572. auto point = p;
  1573. point.translate_by(state().translation);
  1574. // Use the scale only to avoid clipping pixels set in drawing functions that handle
  1575. // scaling and call set_pixel() -- do not scale the pixel.
  1576. if (!clip_rect().contains(point / scale()))
  1577. return;
  1578. set_physical_pixel(point, color, blend);
  1579. }
  1580. void Painter::set_physical_pixel(IntPoint physical_point, Color color, bool blend)
  1581. {
  1582. // This function should only be called after translation, clipping, etc has been handled elsewhere
  1583. // if not use set_pixel().
  1584. auto& dst = m_target->scanline(physical_point.y())[physical_point.x()];
  1585. if (!blend || color.alpha() == 255)
  1586. dst = color.value();
  1587. else if (color.alpha())
  1588. dst = Color::from_argb(dst).blend(color).value();
  1589. }
  1590. Optional<Color> Painter::get_pixel(IntPoint p)
  1591. {
  1592. auto point = p;
  1593. point.translate_by(state().translation);
  1594. if (!clip_rect().contains(point / scale()))
  1595. return {};
  1596. return Color::from_argb(m_target->scanline(point.y())[point.x()]);
  1597. }
  1598. ErrorOr<NonnullRefPtr<Bitmap>> Painter::get_region_bitmap(IntRect const& region, BitmapFormat format, Optional<IntRect&> actual_region)
  1599. {
  1600. VERIFY(scale() == 1);
  1601. auto bitmap_region = region.translated(state().translation).intersected(m_target->rect());
  1602. if (actual_region.has_value())
  1603. actual_region.value() = bitmap_region.translated(-state().translation);
  1604. return m_target->cropped(bitmap_region, format);
  1605. }
  1606. ALWAYS_INLINE void Painter::set_physical_pixel_with_draw_op(u32& pixel, Color color)
  1607. {
  1608. // This always sets a single physical pixel, independent of scale().
  1609. // This should only be called by routines that already handle scale.
  1610. switch (draw_op()) {
  1611. case DrawOp::Copy:
  1612. pixel = color.value();
  1613. break;
  1614. case DrawOp::Xor:
  1615. pixel = color.xored(Color::from_argb(pixel)).value();
  1616. break;
  1617. case DrawOp::Invert:
  1618. pixel = Color::from_argb(pixel).inverted().value();
  1619. break;
  1620. }
  1621. }
  1622. ALWAYS_INLINE void Painter::fill_physical_scanline_with_draw_op(int y, int x, int width, Color color)
  1623. {
  1624. // This always draws a single physical scanline, independent of scale().
  1625. // This should only be called by routines that already handle scale.
  1626. switch (draw_op()) {
  1627. case DrawOp::Copy:
  1628. fast_u32_fill(m_target->scanline(y) + x, color.value(), width);
  1629. break;
  1630. case DrawOp::Xor: {
  1631. auto* pixel = m_target->scanline(y) + x;
  1632. auto* end = pixel + width;
  1633. while (pixel < end) {
  1634. *pixel = Color::from_argb(*pixel).xored(color).value();
  1635. pixel++;
  1636. }
  1637. break;
  1638. }
  1639. case DrawOp::Invert: {
  1640. auto* pixel = m_target->scanline(y) + x;
  1641. auto* end = pixel + width;
  1642. while (pixel < end) {
  1643. *pixel = Color::from_argb(*pixel).inverted().value();
  1644. pixel++;
  1645. }
  1646. break;
  1647. }
  1648. }
  1649. }
  1650. void Painter::draw_physical_pixel(IntPoint physical_position, Color color, int thickness)
  1651. {
  1652. // This always draws a single physical pixel, independent of scale().
  1653. // This should only be called by routines that already handle scale
  1654. // (including scaling thickness).
  1655. VERIFY(draw_op() == DrawOp::Copy);
  1656. if (thickness <= 0)
  1657. return;
  1658. if (thickness == 1) { // Implies scale() == 1.
  1659. auto& pixel = m_target->scanline(physical_position.y())[physical_position.x()];
  1660. return set_physical_pixel_with_draw_op(pixel, Color::from_argb(pixel).blend(color));
  1661. }
  1662. IntRect rect { physical_position, { thickness, thickness } };
  1663. rect.intersect(clip_rect() * scale());
  1664. fill_physical_rect(rect, color);
  1665. }
  1666. void Painter::draw_line(IntPoint a_p1, IntPoint a_p2, Color color, int thickness, LineStyle style, Color alternate_color)
  1667. {
  1668. if (thickness <= 0)
  1669. return;
  1670. if (color.alpha() == 0)
  1671. return;
  1672. auto clip_rect = this->clip_rect() * scale();
  1673. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1674. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1675. auto point1 = to_physical(p1);
  1676. auto point2 = to_physical(p2);
  1677. thickness *= scale();
  1678. auto alternate_color_is_transparent = alternate_color == Color::Transparent;
  1679. // Special case: vertical line.
  1680. if (point1.x() == point2.x()) {
  1681. int const x = point1.x();
  1682. if (x < clip_rect.left() || x > clip_rect.right())
  1683. return;
  1684. if (point1.y() > point2.y())
  1685. swap(point1, point2);
  1686. if (point1.y() > clip_rect.bottom())
  1687. return;
  1688. if (point2.y() < clip_rect.top())
  1689. return;
  1690. int min_y = max(point1.y(), clip_rect.top());
  1691. int max_y = min(point2.y(), clip_rect.bottom());
  1692. if (style == LineStyle::Dotted) {
  1693. for (int y = min_y; y <= max_y; y += thickness * 2)
  1694. draw_physical_pixel({ x, y }, color, thickness);
  1695. } else if (style == LineStyle::Dashed) {
  1696. for (int y = min_y; y <= max_y; y += thickness * 6) {
  1697. draw_physical_pixel({ x, y }, color, thickness);
  1698. draw_physical_pixel({ x, min(y + thickness, max_y) }, color, thickness);
  1699. draw_physical_pixel({ x, min(y + thickness * 2, max_y) }, color, thickness);
  1700. if (!alternate_color_is_transparent) {
  1701. draw_physical_pixel({ x, min(y + thickness * 3, max_y) }, alternate_color, thickness);
  1702. draw_physical_pixel({ x, min(y + thickness * 4, max_y) }, alternate_color, thickness);
  1703. draw_physical_pixel({ x, min(y + thickness * 5, max_y) }, alternate_color, thickness);
  1704. }
  1705. }
  1706. } else {
  1707. for (int y = min_y; y <= max_y; y += thickness)
  1708. draw_physical_pixel({ x, y }, color, thickness);
  1709. draw_physical_pixel({ x, max_y }, color, thickness);
  1710. }
  1711. return;
  1712. }
  1713. // Special case: horizontal line.
  1714. if (point1.y() == point2.y()) {
  1715. int const y = point1.y();
  1716. if (y < clip_rect.top() || y > clip_rect.bottom())
  1717. return;
  1718. if (point1.x() > point2.x())
  1719. swap(point1, point2);
  1720. if (point1.x() > clip_rect.right())
  1721. return;
  1722. if (point2.x() < clip_rect.left())
  1723. return;
  1724. int min_x = max(point1.x(), clip_rect.left());
  1725. int max_x = min(point2.x(), clip_rect.right());
  1726. if (style == LineStyle::Dotted) {
  1727. for (int x = min_x; x <= max_x; x += thickness * 2)
  1728. draw_physical_pixel({ x, y }, color, thickness);
  1729. } else if (style == LineStyle::Dashed) {
  1730. for (int x = min_x; x <= max_x; x += thickness * 6) {
  1731. draw_physical_pixel({ x, y }, color, thickness);
  1732. draw_physical_pixel({ min(x + thickness, max_x), y }, color, thickness);
  1733. draw_physical_pixel({ min(x + thickness * 2, max_x), y }, color, thickness);
  1734. if (!alternate_color_is_transparent) {
  1735. draw_physical_pixel({ min(x + thickness * 3, max_x), y }, alternate_color, thickness);
  1736. draw_physical_pixel({ min(x + thickness * 4, max_x), y }, alternate_color, thickness);
  1737. draw_physical_pixel({ min(x + thickness * 5, max_x), y }, alternate_color, thickness);
  1738. }
  1739. }
  1740. } else {
  1741. for (int x = min_x; x <= max_x; x += thickness)
  1742. draw_physical_pixel({ x, y }, color, thickness);
  1743. draw_physical_pixel({ max_x, y }, color, thickness);
  1744. }
  1745. return;
  1746. }
  1747. // FIXME: Implement dotted/dashed diagonal lines.
  1748. VERIFY(style == LineStyle::Solid);
  1749. int const adx = abs(point2.x() - point1.x());
  1750. int const ady = abs(point2.y() - point1.y());
  1751. if (adx > ady) {
  1752. if (point1.x() > point2.x())
  1753. swap(point1, point2);
  1754. } else {
  1755. if (point1.y() > point2.y())
  1756. swap(point1, point2);
  1757. }
  1758. // FIXME: Implement clipping below.
  1759. int const dx = point2.x() - point1.x();
  1760. int const dy = point2.y() - point1.y();
  1761. int error = 0;
  1762. if (dx > dy) {
  1763. int const y_step = dy == 0 ? 0 : (dy > 0 ? 1 : -1);
  1764. int const delta_error = 2 * abs(dy);
  1765. int y = point1.y();
  1766. for (int x = point1.x(); x <= point2.x(); ++x) {
  1767. if (clip_rect.contains(x, y))
  1768. draw_physical_pixel({ x, y }, color, thickness);
  1769. error += delta_error;
  1770. if (error >= dx) {
  1771. y += y_step;
  1772. error -= 2 * dx;
  1773. }
  1774. }
  1775. } else {
  1776. int const x_step = dx == 0 ? 0 : (dx > 0 ? 1 : -1);
  1777. int const delta_error = 2 * abs(dx);
  1778. int x = point1.x();
  1779. for (int y = point1.y(); y <= point2.y(); ++y) {
  1780. if (clip_rect.contains(x, y))
  1781. draw_physical_pixel({ x, y }, color, thickness);
  1782. error += delta_error;
  1783. if (error >= dy) {
  1784. x += x_step;
  1785. error -= 2 * dy;
  1786. }
  1787. }
  1788. }
  1789. }
  1790. void Painter::draw_triangle_wave(IntPoint a_p1, IntPoint a_p2, Color color, int amplitude, int thickness)
  1791. {
  1792. // FIXME: Support more than horizontal waves
  1793. VERIFY(a_p1.y() == a_p2.y());
  1794. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1795. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1796. auto point1 = to_physical(p1);
  1797. auto point2 = to_physical(p2);
  1798. auto y = point1.y();
  1799. for (int x = 0; x <= point2.x() - point1.x(); ++x) {
  1800. auto y_offset = abs(x % (2 * amplitude) - amplitude) - amplitude;
  1801. draw_physical_pixel({ point1.x() + x, y + y_offset }, color, thickness);
  1802. }
  1803. }
  1804. static bool can_approximate_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control)
  1805. {
  1806. constexpr float tolerance = 0.0015f;
  1807. auto p1x = 3 * control.x() - 2 * p1.x() - p2.x();
  1808. auto p1y = 3 * control.y() - 2 * p1.y() - p2.y();
  1809. auto p2x = 3 * control.x() - 2 * p2.x() - p1.x();
  1810. auto p2y = 3 * control.y() - 2 * p2.y() - p1.y();
  1811. p1x = p1x * p1x;
  1812. p1y = p1y * p1y;
  1813. p2x = p2x * p2x;
  1814. p2y = p2y * p2y;
  1815. return max(p1x, p2x) + max(p1y, p2y) <= tolerance;
  1816. }
  1817. // static
  1818. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1819. {
  1820. struct SegmentDescriptor {
  1821. FloatPoint control_point;
  1822. FloatPoint p1;
  1823. FloatPoint p2;
  1824. };
  1825. static constexpr auto split_quadratic_bezier_curve = [](FloatPoint original_control, FloatPoint p1, FloatPoint p2, auto& segments) {
  1826. auto po1_midpoint = original_control + p1;
  1827. po1_midpoint /= 2;
  1828. auto po2_midpoint = original_control + p2;
  1829. po2_midpoint /= 2;
  1830. auto new_segment = po1_midpoint + po2_midpoint;
  1831. new_segment /= 2;
  1832. segments.enqueue({ po1_midpoint, p1, new_segment });
  1833. segments.enqueue({ po2_midpoint, new_segment, p2 });
  1834. };
  1835. Queue<SegmentDescriptor> segments;
  1836. segments.enqueue({ control_point, p1, p2 });
  1837. while (!segments.is_empty()) {
  1838. auto segment = segments.dequeue();
  1839. if (can_approximate_bezier_curve(segment.p1, segment.p2, segment.control_point))
  1840. callback(segment.p1, segment.p2);
  1841. else
  1842. split_quadratic_bezier_curve(segment.control_point, segment.p1, segment.p2, segments);
  1843. }
  1844. }
  1845. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1846. {
  1847. for_each_line_segment_on_bezier_curve(control_point, p1, p2, callback);
  1848. }
  1849. void Painter::draw_quadratic_bezier_curve(IntPoint control_point, IntPoint p1, IntPoint p2, Color color, int thickness, LineStyle style)
  1850. {
  1851. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1852. if (thickness <= 0)
  1853. return;
  1854. for_each_line_segment_on_bezier_curve(FloatPoint(control_point), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1855. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1856. });
  1857. }
  1858. 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)
  1859. {
  1860. for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback);
  1861. }
  1862. static bool can_approximate_cubic_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control_0, FloatPoint control_1)
  1863. {
  1864. constexpr float tolerance = 0.0015f;
  1865. auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x();
  1866. auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y();
  1867. auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x();
  1868. auto by = 3 * control_1.y() - p1.y() - 2 * p2.y();
  1869. ax *= ax;
  1870. ay *= ay;
  1871. bx *= bx;
  1872. by *= by;
  1873. return max(ax, bx) + max(ay, by) <= tolerance;
  1874. }
  1875. // static
  1876. 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)
  1877. {
  1878. struct ControlPair {
  1879. FloatPoint control_point_0;
  1880. FloatPoint control_point_1;
  1881. };
  1882. struct SegmentDescriptor {
  1883. ControlPair control_points;
  1884. FloatPoint p1;
  1885. FloatPoint p2;
  1886. };
  1887. static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint p1, FloatPoint p2, auto& segments) {
  1888. Array level_1_midpoints {
  1889. (p1 + original_controls.control_point_0) / 2,
  1890. (original_controls.control_point_0 + original_controls.control_point_1) / 2,
  1891. (original_controls.control_point_1 + p2) / 2,
  1892. };
  1893. Array level_2_midpoints {
  1894. (level_1_midpoints[0] + level_1_midpoints[1]) / 2,
  1895. (level_1_midpoints[1] + level_1_midpoints[2]) / 2,
  1896. };
  1897. auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2;
  1898. segments.enqueue({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint });
  1899. segments.enqueue({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 });
  1900. };
  1901. Queue<SegmentDescriptor> segments;
  1902. segments.enqueue({ { control_point_0, control_point_1 }, p1, p2 });
  1903. while (!segments.is_empty()) {
  1904. auto segment = segments.dequeue();
  1905. if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1))
  1906. callback(segment.p1, segment.p2);
  1907. else
  1908. split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments);
  1909. }
  1910. }
  1911. void Painter::draw_cubic_bezier_curve(IntPoint control_point_0, IntPoint control_point_1, IntPoint p1, IntPoint p2, Color color, int thickness, Painter::LineStyle style)
  1912. {
  1913. for_each_line_segment_on_cubic_bezier_curve(FloatPoint(control_point_0), FloatPoint(control_point_1), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1914. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1915. });
  1916. }
  1917. // static
  1918. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint p1, FloatPoint p2, FloatPoint center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint, FloatPoint)>& callback)
  1919. {
  1920. if (radii.x() <= 0 || radii.y() <= 0)
  1921. return;
  1922. auto start = p1;
  1923. auto end = p2;
  1924. if (theta_delta < 0) {
  1925. swap(start, end);
  1926. theta_1 = theta_1 + theta_delta;
  1927. theta_delta = fabsf(theta_delta);
  1928. }
  1929. auto relative_start = start - center;
  1930. auto a = radii.x();
  1931. auto b = radii.y();
  1932. // The segments are at most 1 long
  1933. auto largest_radius = max(a, b);
  1934. float theta_step = AK::atan2(1.f, (float)largest_radius);
  1935. FloatPoint current_point = relative_start;
  1936. FloatPoint next_point = { 0, 0 };
  1937. float sin_x_axis, cos_x_axis;
  1938. AK::sincos(x_axis_rotation, sin_x_axis, cos_x_axis);
  1939. auto rotate_point = [sin_x_axis, cos_x_axis](FloatPoint& p) {
  1940. auto original_x = p.x();
  1941. auto original_y = p.y();
  1942. p.set_x(original_x * cos_x_axis - original_y * sin_x_axis);
  1943. p.set_y(original_x * sin_x_axis + original_y * cos_x_axis);
  1944. };
  1945. for (float theta = theta_1; theta <= theta_1 + theta_delta; theta += theta_step) {
  1946. float s, c;
  1947. AK::sincos(theta, s, c);
  1948. next_point.set_x(a * c);
  1949. next_point.set_y(b * s);
  1950. rotate_point(next_point);
  1951. callback(current_point + center, next_point + center);
  1952. current_point = next_point;
  1953. }
  1954. callback(current_point + center, end);
  1955. }
  1956. // static
  1957. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint p1, FloatPoint p2, FloatPoint center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint, FloatPoint)>&& callback)
  1958. {
  1959. for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, callback);
  1960. }
  1961. void Painter::draw_elliptical_arc(IntPoint p1, IntPoint p2, IntPoint center, FloatPoint radii, float x_axis_rotation, float theta_1, float theta_delta, Color color, int thickness, LineStyle style)
  1962. {
  1963. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1964. if (thickness <= 0)
  1965. return;
  1966. for_each_line_segment_on_elliptical_arc(FloatPoint(p1), FloatPoint(p2), FloatPoint(center), radii, x_axis_rotation, theta_1, theta_delta, [&](FloatPoint fp1, FloatPoint fp2) {
  1967. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1968. });
  1969. }
  1970. void Painter::add_clip_rect(IntRect const& rect)
  1971. {
  1972. state().clip_rect.intersect(rect.translated(translation()));
  1973. state().clip_rect.intersect(m_target->rect()); // FIXME: This shouldn't be necessary?
  1974. }
  1975. void Painter::clear_clip_rect()
  1976. {
  1977. state().clip_rect = m_clip_origin;
  1978. }
  1979. PainterStateSaver::PainterStateSaver(Painter& painter)
  1980. : m_painter(painter)
  1981. {
  1982. m_painter.save();
  1983. }
  1984. PainterStateSaver::~PainterStateSaver()
  1985. {
  1986. m_painter.restore();
  1987. }
  1988. void Painter::stroke_path(Path const& path, Color color, int thickness)
  1989. {
  1990. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1991. if (thickness <= 0)
  1992. return;
  1993. FloatPoint cursor;
  1994. for (auto& segment : path.segments()) {
  1995. switch (segment.type()) {
  1996. case Segment::Type::Invalid:
  1997. VERIFY_NOT_REACHED();
  1998. break;
  1999. case Segment::Type::MoveTo:
  2000. cursor = segment.point();
  2001. break;
  2002. case Segment::Type::LineTo:
  2003. draw_line(cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  2004. cursor = segment.point();
  2005. break;
  2006. case Segment::Type::QuadraticBezierCurveTo: {
  2007. auto through = static_cast<QuadraticBezierCurveSegment const&>(segment).through();
  2008. draw_quadratic_bezier_curve(through.to_type<int>(), cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  2009. cursor = segment.point();
  2010. break;
  2011. }
  2012. case Segment::Type::CubicBezierCurveTo: {
  2013. auto& curve = static_cast<CubicBezierCurveSegment const&>(segment);
  2014. auto through_0 = curve.through_0();
  2015. auto through_1 = curve.through_1();
  2016. draw_cubic_bezier_curve(through_0.to_type<int>(), through_1.to_type<int>(), cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  2017. cursor = segment.point();
  2018. break;
  2019. }
  2020. case Segment::Type::EllipticalArcTo:
  2021. auto& arc = static_cast<EllipticalArcSegment const&>(segment);
  2022. draw_elliptical_arc(cursor.to_type<int>(), segment.point().to_type<int>(), arc.center().to_type<int>(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness);
  2023. cursor = segment.point();
  2024. break;
  2025. }
  2026. }
  2027. }
  2028. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  2029. {
  2030. VERIFY(scale() == 1); // FIXME: Add scaling support.
  2031. Detail::fill_path<Detail::FillPathMode::PlaceOnIntGrid>(*this, path, color, winding_rule);
  2032. }
  2033. void Painter::blit_disabled(IntPoint location, Gfx::Bitmap const& bitmap, IntRect const& rect, Palette const& palette)
  2034. {
  2035. auto bright_color = palette.threed_highlight();
  2036. auto dark_color = palette.threed_shadow1();
  2037. blit_filtered(location.translated(1, 1), bitmap, rect, [&](auto) {
  2038. return bright_color;
  2039. });
  2040. blit_filtered(location, bitmap, rect, [&](Color src) {
  2041. int gray = src.to_grayscale().red();
  2042. if (gray > 160)
  2043. return bright_color;
  2044. return dark_color;
  2045. });
  2046. }
  2047. void Painter::blit_tiled(IntRect const& dst_rect, Gfx::Bitmap const& bitmap, IntRect const& rect)
  2048. {
  2049. auto tile_width = rect.width();
  2050. auto tile_height = rect.height();
  2051. auto dst_right = dst_rect.right();
  2052. auto dst_bottom = dst_rect.bottom();
  2053. for (int tile_y = dst_rect.top(); tile_y < dst_bottom; tile_y += tile_height) {
  2054. for (int tile_x = dst_rect.left(); tile_x < dst_right; tile_x += tile_width) {
  2055. IntRect tile_src_rect = rect;
  2056. auto tile_x_overflow = tile_x + tile_width - dst_right;
  2057. if (tile_x_overflow > 0) {
  2058. tile_src_rect.set_width(tile_width - tile_x_overflow);
  2059. }
  2060. auto tile_y_overflow = tile_y + tile_height - dst_bottom;
  2061. if (tile_y_overflow > 0) {
  2062. tile_src_rect.set_height(tile_height - tile_y_overflow);
  2063. }
  2064. blit(IntPoint(tile_x, tile_y), bitmap, tile_src_rect);
  2065. }
  2066. }
  2067. }
  2068. DeprecatedString parse_ampersand_string(StringView raw_text, Optional<size_t>* underline_offset)
  2069. {
  2070. if (raw_text.is_empty())
  2071. return DeprecatedString::empty();
  2072. StringBuilder builder;
  2073. for (size_t i = 0; i < raw_text.length(); ++i) {
  2074. if (raw_text[i] == '&') {
  2075. if (i != (raw_text.length() - 1) && raw_text[i + 1] == '&') {
  2076. builder.append(raw_text[i]);
  2077. ++i;
  2078. } else if (underline_offset && !(*underline_offset).has_value()) {
  2079. *underline_offset = i;
  2080. }
  2081. continue;
  2082. }
  2083. builder.append(raw_text[i]);
  2084. }
  2085. return builder.to_deprecated_string();
  2086. }
  2087. void Gfx::Painter::draw_ui_text(Gfx::IntRect const& rect, StringView text, Gfx::Font const& font, Gfx::TextAlignment text_alignment, Gfx::Color color)
  2088. {
  2089. Optional<size_t> underline_offset;
  2090. auto name_to_draw = parse_ampersand_string(text, &underline_offset);
  2091. Gfx::IntRect text_rect { 0, 0, static_cast<int>(ceilf(font.width(name_to_draw))), static_cast<int>(ceilf(font.pixel_size())) };
  2092. text_rect.align_within(rect, text_alignment);
  2093. draw_text(text_rect, name_to_draw, font, text_alignment, color);
  2094. if (underline_offset.has_value()) {
  2095. Utf8View utf8_view { name_to_draw };
  2096. float width = 0;
  2097. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  2098. if (utf8_view.byte_offset_of(it) >= underline_offset.value()) {
  2099. int y = text_rect.bottom() + 1;
  2100. int x1 = text_rect.left() + width;
  2101. int x2 = x1 + font.glyph_or_emoji_width(*it);
  2102. draw_line({ x1, y }, { x2, y }, color);
  2103. break;
  2104. }
  2105. width += font.glyph_or_emoji_width(*it) + font.glyph_spacing();
  2106. }
  2107. }
  2108. }
  2109. void Painter::draw_text_run(IntPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2110. {
  2111. draw_text_run(baseline_start.to_type<float>(), string, font, color);
  2112. }
  2113. void Painter::draw_text_run(FloatPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2114. {
  2115. auto pixel_metrics = font.pixel_metrics();
  2116. float x = baseline_start.x();
  2117. float y = baseline_start.y() - pixel_metrics.ascent;
  2118. float space_width = font.glyph_or_emoji_width(' ');
  2119. u32 last_code_point = 0;
  2120. for (auto code_point_iterator = string.begin(); code_point_iterator != string.end(); ++code_point_iterator) {
  2121. auto code_point = *code_point_iterator;
  2122. if (should_paint_as_space(code_point)) {
  2123. x += space_width + font.glyph_spacing();
  2124. last_code_point = code_point;
  2125. continue;
  2126. }
  2127. // FIXME: this is probably not the real space taken for complex emojis
  2128. x += font.glyphs_horizontal_kerning(last_code_point, code_point);
  2129. draw_glyph_or_emoji(FloatPoint { x, y }, code_point_iterator, font, color);
  2130. x += font.glyph_or_emoji_width(code_point) + font.glyph_spacing();
  2131. last_code_point = code_point;
  2132. }
  2133. }
  2134. void Painter::draw_scaled_bitmap_with_transform(IntRect const& dst_rect, Bitmap const& bitmap, FloatRect const& src_rect, AffineTransform const& transform, float opacity, Painter::ScalingMode scaling_mode)
  2135. {
  2136. if (transform.is_identity_or_translation()) {
  2137. translate(transform.e(), transform.f());
  2138. draw_scaled_bitmap(dst_rect, bitmap, src_rect, opacity, scaling_mode);
  2139. translate(-transform.e(), -transform.f());
  2140. } else {
  2141. // The painter has an affine transform, we have to draw through it!
  2142. // FIXME: This is *super* inefficient.
  2143. // What we currently do, roughly:
  2144. // - Map the destination rect through the context's transform.
  2145. // - Compute the bounding rect of the destination quad.
  2146. // - For each point in the computed bounding rect, reverse-map it to a point in the source image.
  2147. // - Sample the source image at the computed point.
  2148. // - Set or blend (depending on alpha values) one pixel in the canvas.
  2149. // - Loop.
  2150. // FIXME: Painter should have an affine transform as part of its state and handle all of this instead.
  2151. auto inverse_transform = transform.inverse();
  2152. if (!inverse_transform.has_value())
  2153. return;
  2154. auto destination_quad = transform.map_to_quad(dst_rect.to_type<float>());
  2155. auto destination_bounding_rect = destination_quad.bounding_rect().to_rounded<int>();
  2156. Gfx::AffineTransform source_transform;
  2157. source_transform.translate(src_rect.x(), src_rect.y());
  2158. source_transform.scale(src_rect.width() / dst_rect.width(), src_rect.height() / dst_rect.height());
  2159. source_transform.translate(-dst_rect.x(), -dst_rect.y());
  2160. for (int y = destination_bounding_rect.y(); y <= destination_bounding_rect.bottom(); ++y) {
  2161. for (int x = destination_bounding_rect.x(); x <= destination_bounding_rect.right(); ++x) {
  2162. auto destination_point = Gfx::IntPoint { x, y };
  2163. if (!clip_rect().contains(destination_point))
  2164. continue;
  2165. if (!destination_quad.contains(destination_point.to_type<float>()))
  2166. continue;
  2167. auto source_point = source_transform.map(inverse_transform->map(destination_point)).to_rounded<int>();
  2168. if (!bitmap.rect().contains(source_point))
  2169. continue;
  2170. auto source_color = bitmap.get_pixel(source_point);
  2171. if (source_color.alpha() == 0)
  2172. continue;
  2173. if (source_color.alpha() == 255) {
  2174. set_pixel(destination_point, source_color);
  2175. continue;
  2176. }
  2177. auto dst_color = target()->get_pixel(destination_point);
  2178. set_pixel(destination_point, dst_color.blend(source_color));
  2179. }
  2180. }
  2181. }
  2182. }
  2183. }